
[英]Parse XML with PHP and get nested level element value and attribute value
[英]Help parse XML to PHP by attribute value
有人可以帮我解析一下吗。 我有以下 XML。 我需要获取与 "75" max-width
匹配的photo-url
的值。 如何在 PHP $xml->posts->post['photo-url']
.... 中过滤它?
<photo-url max-width="100">
image1.jpg
</photo-url>
<photo-url max-width="75">
image2.jpg
</photo-url>
使用 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
}
使用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);
}
您可以使用 XPath: //photo-url[@max-width = '75']
。 它将 select 所有满足此条件photo-url
。 对于 select 仅使用第一photo-url
: //photo-url[@max-width = '75'][1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.