SimpleXML是DOM的抽象。 $ child和$ child [0]是独立的SimpleXMLElement对象,但访问相同的DOM节点。 unset()不仅会删除SimpleXMLElement对象,还会从DOM中删除节点。
所以在第二个SimpleXMLElement对象之后引用一个被删除的DOM节点。
稍加修改你的榜样,你可以得到一个警告吧:
$concerts = simplexml_load_string($xml);
foreach ($concerts->xpath('/*/cars/*') as $child) {
echo "Before= " .$child->asXml() ."\n";
unset($child[0]);
echo "After= " .$child->asXml() ."\n";
}
输出:
Before= <car_id>26395593</car_id>
Warning: SimpleXMLElement::asXML(): Node no longer exists in /tmp/e... on line 19
After=
Before= <standart>0</standart>
Warning: SimpleXMLElement::asXML(): Node no longer exists in /tmp/e... on line 19
After=
Before= <model>2</model>
Warning: SimpleXMLElement::asXML(): Node no longer exists in /tmp/e... on line 19
After=
你应该避免解封的SimpleXMLElement对象。如果您需要以其他格式存储数据,请保留原始文档相同,从中读取值并创建新的XML文档。
为 “断开” 从XML节点的值,施放SimpleXMLElement对象为标:
$concerts = simplexml_load_string($xml);
foreach ($concerts->xpath('/*/cars/*') as $child) {
$value = (string)$child;
echo "Before= " .$value."\n";
unset($child[0]);
echo "After= " .$value ."\n";
}
输出:
Before= 26395593
After= 26395593
Before= 0
After= 0
Before= 2
After= 2
来源
2015-01-15 10:16:29
ThW
它的正常工作。也许你有不同的代码比问题? http://sandbox.onlinephpfunctions.com/code/d928e46b2dbb29eef9f53f6e40447ba4440c40e5 – Justinas