0

我正在尝试更改 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 专家,也不知道如何以任何其他方式访问命名空间元素……我该如何更改这些值?我到处搜索,但只找到如何读取值的说明。

4

1 回答 1

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] 我的元素现在是:[其他]
    我的元素是:[香蕉] 我的元素现在是:[别的]

    
    
      别的东西
      别的东西
      樱桃
    

    

希望这有帮助。

于 2013-03-23T01:32:21.417 回答