I am trying to iterate over set of nodes given by xpath and set certain attribute for each node. However it works only for nodes withou content or with empty (whitespace) content. I have tried 2 approaches but with the same result (maybe they are both the same on some deeper level, dunno). The commented line is the second approach.
$temp = simplexml_load_string (
'<toolbox>
<hammer/>
<screwdriver> </screwdriver>
<knife>
sharp
</knife>
</toolbox>' );
echo "vanilla toolbox: ";
print_r($temp);
$nodes = $temp->xpath('//*[not(@id)]');
foreach($nodes as $obj) {
$tempdom = dom_import_simplexml($obj);
$tempdom->setAttributeNode(new DOMAttr('id', 5));
//$obj->addAttribute('bagr', 5);
}
echo "processed toolbox: ";
print_r($temp);
This is output. Attribute id is missing in node knife.:
vanilla toolbox: SimpleXMLElement Object
(
[hammer] => SimpleXMLElement Object
(
)
[screwdriver] => SimpleXMLElement Object
(
[0] =>
)
[knife] =>
sharp
)
processed toolbox: SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 5
)
[hammer] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 5
)
)
[screwdriver] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 5
)
[0] =>
)
[knife] =>
sharp
I’m unable to reproduce what you describe, the changed XML is:
Demo
It’s exactly your code, maybe you’re using a different LIBXML version? See the
LIBXML_VERSIONconstant (codepad viper has 20626 (2.6.26)).But probably it’s just only the
print_routput for aSimpleXMLElementobject.It does not output the attributes for the last element, even on a brand new object, but it’s still possible to access the attribute. Demo.
You will see when you
print_r($temp->knife['id']);that the attribute is set (as you can see in the earlier XML output).