smatter
smatter

Reputation: 29178

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?

Upvotes: 2

Views: 219

Answers (2)

Sahil Gulati
Sahil Gulati

Reputation: 15141

Here we are using DOMDocument for setting attribute in a tag.

<?php

ini_set('display_errors', 1);
libxml_use_internal_errors(true);
$domObject = new DOMDocument();
$domObject->loadHTML('<node name="nodeA">this is a node</node>',LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
$result=$domObject->getElementsByTagName("node")->item(0);
$result->setAttribute("newattrib","attribA");
echo $result->ownerDocument->saveHTML();

Output: <node name="nodeA" newattrib="attribA">this is a node</node>

Upvotes: 0

splash58
splash58

Reputation: 26153

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

Upvotes: 1

Related Questions