帮助按属性值将XML解析为PHP

时间:2011-07-20 14:45:59

标签: php xml xpath

有人可以帮我解析一下。我有以下XML。我需要获得匹配“75”photo-url的{​​{1}}的值。如何在PHP中过滤它 max-width ....?

$xml->posts->post['photo-url']

3 个答案:

答案 0 :(得分:4)

使用PHP DOM

$dom = new DomDocument;
$dom->loadXml('
<root>
    <photo-url max-width="100">image1.jpg</photo-url>
    <photo-url max-width="75">image2.jpg</photo-url>
</root>
');

$xpath = new DomXpath($dom);
foreach ($xpath->query('//photo-url[@max-width="75"]') as $photoUrlNode) {
    echo $photoUrlNode->nodeValue; // will be image2.jpg
}

答案 1 :(得分:3)

使用SimpleXMLElement和xpath查询。

$xml = new SimpleXMLElement($your_xml_string);
$result = $xml->xpath('//photo-url[@max-width="75"]');

// Loop over all the <photo-url> nodes and dump their contents
foreach ($result as $node ) {
   print_r($node);
   $image = strip_tags($node->asXML);
}

答案 2 :(得分:1)

您可以使用XPath://photo-url[@max-width = '75']。它将选择满足此条件的所有photo-url。要仅选择第一个photo-url,请使用此//photo-url[@max-width = '75'][1]

相关问题