2014-10-22 57 views
2

在我所看到的XML结构的simplexml的所有例子是这样的:的SimpleXML与多个标签

<examples> 
<example> 
</example> 
<example> 
</example> 
<example> 
</example> 
</examples> 

但是我处理XML形式:

<examples> 
    <example> 
    </example> 
    <example> 
    </example> 
    <example> 
    </example> 
</examples> 
<app> 
<appdata> 
<error> 
<Details> 
<ErrorCode>101</ErrorCode> 
<ErrorDescription>Invalid Username and Password</ErrorDescription> 
<ErrorSeverity>3</ErrorSeverity> 
<ErrorSource /> 
<ErrorDetails /> 
</Details> 
</error> 
<items> 
<item> 
</item> 
<item> 
</item> 
</items> 
</appdata> 
</app> 

我会喜欢跳过示例的东西,并直接进入应用程序标记,并检查错误错误码是否存在,如果不存在,请转到items数组并循环。

我处理这个电流的方法是:

$items = new SimpleXMLElement($xml_response); 
foreach($items as $item){ 
     //in here I check the presence of the object properties 
    } 

有没有更好的办法?问题是xml结构有时会改变顺序,所以我希望能够直接转到xml的特定部分。

+2

这不是你正在处理的XML,除非它有共同的根节点。 – dfsq 2014-10-22 11:04:41

回答

1

这种东西很容易用XPath,而且很方便,SimpleXML has an xpath function内置到它里面! XPath允许您根据祖先,后代,属性,值等选择图中的节点。

下面是使用SimpleXML的xpath函数从XML中提取数据的示例。请注意,我为您发布的示例添加了一个额外的父元素,以便XML进行验证。

$sxo = new SimpleXMLElement($xml); 
# this selects all 'error' elements with parent 'appdata', which has parent 'app' 
$error = $sxo->xpath('//app/appdata/error'); 

if ($error) { 
    # go through the error elements... 
    while(list(, $node) = each($error)) { 
     # get the error details 
     echo "Found an error!" . PHP_EOL; 
     echo $node->Details->ErrorCode 
     . ", severity " . $node->Details->ErrorSeverity 
     . ": " . $node->Details->ErrorDescription . PHP_EOL; 
    } 
} 

输出:

Found an error! 
101, severity 3: Invalid Username and Password 

这里是另外一个例子 - 我编辑的XML摘录略微显示效果也比较好这里:

// edited <items> section of the XML you posted: 
<items> 
    <item>Item One 
    </item> 
    <item>Item Two 
    </item> 
</items> 

# this selects all 'item' elements under appdata/items: 
$items = $sxo->xpath('//appdata/items/item'); 
foreach ($items as $i) { 
    echo "Found item; value: " . $i . PHP_EOL; 
} 

输出:

Found item; value: Item One 
Found item; value: Item Two 

有更多的信息在SimpleXML XPath文档中,并尝试zvon.org XPath tutorials - 它们为XPath 1.0语法提供了良好的基础。

+0

感谢您的回答。我实际上是在Niloct的推动下自己到达那里才让我读到xpath的。 – 2014-10-22 16:06:57

+1

虽然我选择了它,但您的答案更有帮助。 – 2014-10-22 16:07:23