Php 具有多个标记的Simplexml

Php 具有多个标记的Simplexml,php,simplexml,Php,Simplexml,在所有simplexml示例中,我看到xml的结构如下所示: <examples> <example> </example> <example> </example> <example> </example> </examples> 有更好的办法吗?问题是xml结构有时会改变顺序,因此我希望能够直接转到xml的特定部分。使用XPath这种东西非常容易,而且很方便地内置在其中!XPath允许您根据节点

在所有simplexml示例中,我看到xml的结构如下所示:

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

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

使用XPath这种东西非常容易,而且很方便地内置在其中!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
Found item; value: Item One
Found item; value: Item Two
下面是另一个示例—我稍微编辑了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;
}

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

这不是您要处理的XML,除非它有公共根节点。谢谢您的回答。事实上,我是在Niloct的推动下亲自到达那里的,目的是让我阅读xpath。虽然你的答案更有用,但我还是选择了它。
// 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