php - 通过属性值 PHP 对 XML 进行排序

标签 php xml simplexml

所以我有一个 XML 文件,我试图根据属性“order”按顺序循环。

这是一个例子:

<page>
<talentTrees>
<tree name="Football" order="2">
<tree name="Baseball" order="0">
<tree name="Frisbee" order="1">
</talentTrees>
</page>

我的目标是使用 foreach 遍历每棵“树”,但我想按顺序属性的顺序读取它们:棒球、飞盘、足球。 (0,1,2).

抱歉英语不好,不是我的母语。

最佳答案

为了将来引用,您可以使用以下内容通过 XPath 查询节点并通过 XPath 对结果进行排序:SimpleDOM .在此示例中,我对所有 <tree/> 进行排序节点按 order 的值属性:

include 'SimpleDOM.php';

$page = simpledom_load_string('<page>
    <talentTrees>
        <tree name="Football" order="2"/>
        <tree name="Baseball" order="0"/>
        <tree name="Frisbee" order="1"/>
    </talentTrees>
</page>');

$nodes = $page->sortedXPath('//tree', '@order');

foreach ($nodes as $node)
{
    echo $node->asXML(), "\n";
}

关于php - 通过属性值 PHP 对 XML 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1359224/

相关文章:

php - SimpleXML:选择具有特定属性值的元素

php - 来自字符串的关键字

javascript - 将 PHP 数组发送到回显字符串中调用的 JS 函数

php - 为什么这个 PHP SimpleXML XPath 找不到值?

PHP DOMDocument 没有正确格式化输出

xpath php 属性不起作用?

PHP 和 MYSQL 按小数列排序

android - 在Android上使用XStream时如何注释order字段?

Java(JAXP) 和 XSLT : Overwriting the XML file

xml - 如何将特定属性转换为元素