XML如果未设置节点不能获得变量值

时间:2015-01-15 09:01:47

标签: php xml variables foreach unset

所以我从XML字符串中取消了每个元素

$xml = <<< XML
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<cars>  
<car_id>26395593</car_id>
<standart>0</standart>
<model>2</model> 
</cars>
</xml>
XML;

//将XML加载到变量中;

$concerts = simplexml_load_string($xml);

foreach ($concerts->xpath('/*/cars/*') as $child) {
    $chil = $child;

    echo "Before= " .$chil ."\n";
    unset( $child[0] );
    echo "After= " .$chil ."\n";
}

现在结果就像这样

Before= 26395593
After= 
Before= 0
After= 
Before= 2
After=

为什么$chil变量也未设置?如何将$child值保存到变量?

1 个答案:

答案 0 :(得分:2)

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