所以我有一个 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/