Search code examples
phpxmlsimplexmldomdocument

How to add an attribute to an XML Element in PHP without the xml header?


I need to add a new attribute to xml elements stored in DB. This is not a complete XML, but just XML elements in the DB.

When I do the following,

$node_xml = simplexml_load_string('<node name="nodeA">this is a node</node>');
$node_xml->addAttribute('newattrib', "attribA");
$res_xml = $node_xml->asXML();

I get $res_xml as:

"<?xml version=\"1.0\"?>\n<node name=\"nodeA\" newattrib=\"attribA\">this is a node</node>\n"

How do I eliminate the <?xml version=\"1.0\"?> part without doing a string manipulation?


Solution

  • Add the root level and then get the node but not the full xml. In that case the header will not be echoed

    $string = '<node name="nodeA">this is a node</node>';
    $node_xml = simplexml_load_string('<root>'. $string .'</root>');
    $node = $node_xml->children()[0];
    $node->addAttribute('newattrib', "attribA");
    
    echo $res_xml = $node->asXML(); // <node name="nodeA" newattrib="attribA">this is a node</node>
    

    demo