simpleXML基于属性获取节点子节点

时间:2012-03-14 05:42:41

标签: php xml simplexml

我试图通过其中一个属性解析我引用的节点的值。但我不确定语法

XML:

<data>

  <poster name="E-Verify" id="everify">

    <full_image url="e-verify-swa-poster.jpg"/>

    <full_other url=""/>

  </poster>


  <poster name="Minimum Wage" id="minwage">

    <full_image url="minwage.jpg"/>

    <full_other url="spa_minwage.jpg"/>

  </poster>
</data>

这里是我想要获取full_image的url值,其中poster id等于minwage:

$xml = simplexml_load_file('PosterData.xml');
$main_url = $xml->full_image[name] where poster[id] = "minwage";
//something like that.
echo $main_url;

Result: minwage.jpg

如果有人有任何资源可以覆盖这些内容,请分享。

3 个答案:

答案 0 :(得分:22)

您应该可以使用SimpleXMLElement::xpath()在简单的XML文档上运行xpath query

$xml = simplexml_load_file('PosterData.xml');
$main_url = $xml->xpath('name[@id="minwage"]/full_image')[0];

echo $main_url;

答案 1 :(得分:7)

只需循环播放海报元素并记住将属性值强制转换为字符串,因为您希望将它们(并可能将它们输出)作为字符串进行比较:

$xml = simplexml_load_file('PosterData.xml');

foreach ($xml->poster as $poster) {
    if ((string) $poster['id'] == 'minwage') {
        echo (string) $poster->full_image['url'];
    }
}

答案 2 :(得分:1)

您可以使用:

$object = simplexml_load_string('<data><poster name="E-Verify" id="everify"><full_image url="e-verify-swa-poster.jpg"/><full_other url=""/></poster><poster name="Minimum Wage" id="minwage"><full_image url="minwage.jpg"/><full_other url="spa_minwage.jpg"/></poster></data>');

foreach ($object as $value) {
    echo "URL: ".$value->full_image->attributes();
    echo "<br>";
}

如果调用外部文件,请使用simplexml_load_file('Some external file.xml')