Reputation: 53
I'm trying to change an XML value and then save it back as XML. Works fine when I change elements that have no namespace. Problem is, when the value I want to change is in a namespace; I can find and print out, but any changes get ignored; like this:
$ns = $xmlsingle->children('mynamespace');
foreach ($ns as $myelement)
{
echo "my element is: [$myelement]";
//I can change it:
$myelement = "something else";
echo "my element is now: [$myelement]"; //yay, value is changed!
}
//GREAT!
//But when I save the XML back, the value is not changed... apparently the children method creates a new object; not a link to the existing object
//So if I copy/paste the code above, I have the original value, not the changed value
$ns2 = $xmlsingle->children('mynamespace');
foreach ($ns2 as $myelement)
{
echo "my element is UNCHANGED! [$myelement]";
}
//So my change's not done when I save the XML.
$xmlsingle->asXML(); //This XML is exacly the same as the original XML, without changes to the namespaced elements.
**Please ignore any silly errors that might not compile, I re-typed the text from my original code, otherwise it would be too large; the code works, just the NAMESPACED element's values are unchanged when I put it back to XML.
I'm not a PHP expert and I don't know how to access namespaced elements in any other way... How could I change those values? I searched everywhere but only find instructions how to READ the values.
Upvotes: 0
Views: 95
Reputation: 331
try something like this:
$xml = '
<example xmlns:foo="bar">
<foo:a>Apple</foo:a>
<foo:b>Banana</foo:b>
<c>Cherry</c>
</example>';
$xmlsingle = new \SimpleXMLElement($xml);
echo "<pre>\n\n";
echo $xmlsingle->asXML();
echo "\n\n";
$ns = $xmlsingle->children('bar');
foreach ($ns as $i => $myelement){
echo "my element is: [$myelement] ";
//$myelement = "something else"; // <-- OLD
$ns->$i = 'something else'; // <-- NEW
echo "my element is now: [$myelement]"; //yay, value is changed!
echo "\n";
}
echo "\n\n";
echo $xmlsingle->asXML();
echo "\n</pre>";
and result should be:
Apple Banana Cherry my element is: [Apple] my element is now: [something else] my element is: [Banana] my element is now: [something else] something else something else Cherry
hope this help.
Upvotes: 1