Selecting attribute values based on another attribute value with SimpleXML [duplicate]

安稳与你 提交于 2019-12-11 02:12:59

问题


I'm trying to display an image using an xml file and SimpleXML

The XML code is

<icons>
  <icon size="tiny"    href="/FF02-tiny.jpg"    />
  <icon size="sidebar" href="/FF02-sidebar.jpg" />
  <icon size="full"    href="/FF02-full.jpg"    />
</icons>

I want to get the href attribute for the size="full" line.

I've tried

icons->icon->attributes()->href

but this just gives me the first 'tiny' size. I know I should be using xpath but I am lost.


回答1:


$icons->icon will give you a SimpleXMLElement object that gives access to all icon child-elements of the $icons object.

From there you need to select which icon you want to get the attribute for. That works with array-like access and a numeric value for the zero-index child element and a string value for the attribute:

// specify what icon you want (third)
// and the attribute (href)
$icons->icon[2]['href'];

You find that documented in the PHP manual with the SimpleXML basic examples (Example #3 and Example #5).

However this does not work if the position of the element you look for changes. So it's suggested that you use a more specific xpath-expression instead.




回答2:


Yes, you can select the attribute node with an xpath expression:

list($iconHref) = $xml->xpath("//icon[@size='full']/@href");
echo $iconHref;


来源:https://stackoverflow.com/questions/14979588/selecting-attribute-values-based-on-another-attribute-value-with-simplexml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!