我正在尝试更改XML值,然后将其另存为XML。 更改没有命名空间的元素时工作正常。问题是,当我想要更改的值在命名空间中时;我可以找到并打印出来,但任何变化都会被忽略;像这样:
$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.
**请忽略任何可能无法编译的愚蠢错误,我从原始代码中重新输入文本,否则会太大;代码工作,当我把它放回XML时,只有NAMESPACED元素的值不变。
我不是PHP专家,我不知道如何以任何其他方式访问命名空间元素......我怎么能改变这些值?我到处搜索,但只找到如何阅读值的说明。
答案 0 :(得分:1)
尝试这样的事情:
$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>";
,结果应为:
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希望这有帮助。