XML 如果未设置节点无法获取变量值

XML if unset node cant get variable value

所以我取消了 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 值保存到变量?

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 文档(如果您需要以其他格式存储数据)。

到 "disconnect" 来自 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