使用 SimpleXML 根据另一个属性值选择属性值 [英] Selecting attribute values based on another attribute value with SimpleXML
问题描述
我正在尝试使用 xml 文件和 SimpleXML 显示图像
I'm trying to display an image using an xml file and SimpleXML
XML 代码是
<icons>
<icon size="tiny" href="/FF02-tiny.jpg" />
<icon size="sidebar" href="/FF02-sidebar.jpg" />
<icon size="full" href="/FF02-full.jpg" />
</icons>
我想获取 size="full"
行的 href
属性.
I want to get the href
attribute for the size="full"
line.
我试过了
icons->icon->attributes()->href
但这只是给了我第一个 'tiny'
大小.我知道我应该使用 xpath,但我迷路了.
but this just gives me the first 'tiny'
size. I know I should be using xpath but I am lost.
推荐答案
$icons->icon
会给你一个 SimpleXMLElement
对象,它可以访问所有 icon
$icons
对象的子元素.
$icons->icon
will give you a SimpleXMLElement
object that gives access to all icon
child-elements of the $icons
object.
从那里您需要选择要为其获取属性的图标.这适用于 array-like 访问和零索引子元素的数值和属性的字符串值:
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'];
您发现 PHP 手册中的SimpleXML 基本示例 (示例#3 和示例#5).
You find that documented in the PHP manual with the SimpleXML basic examples (Example #3 and Example #5).
但是,如果您要查找的元素的位置发生变化,这将不起作用.因此,建议您改用更具体的 xpath 表达式.
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.
这篇关于使用 SimpleXML 根据另一个属性值选择属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!