我有一些xml:
<release id="2276808" status="Accepted">
<images>
<image height="600" type="primary" uri="http://s.dsimg.com/image/R-2276808-1302966902.jpeg" uri150="http://s.dsimg.com/image/R-150-2276808-1302966902.jpeg" width="600"/>
<image height="600" type="secondary" uri="http://s.dsimg.com/image/R-2276808-1302966912.jpeg" uri150="http://s.dsimg.com/image/R-150-2276808-1302966912.jpeg" width="600"/>
<image height="600" type="secondary" uri="http://s.dsimg.com/image/R-2276808-1302966919.jpeg" uri150="http://s.dsimg.com/image/R-150-2276808-1302966919.jpeg" width="600"/><image height="600" type="secondary" uri="http://s.dsimg.com/image/R-2276808-1302966929.jpeg" uri150="http://s.dsimg.com/image/R-150-2276808-1302966929.jpeg" width="600"/>
</images> ...
我使用的是SimpleXML和php5.3。
我想将目标指向type="primary"
所在的image
节点,并返回uri属性的值。
我得到的最接近的是:
$xml->xpath('/release/images/image[@type="primary"]')->attributes()->uri;
由于在CCD_ 4之后不能调用CCD_。
实现属性的纯XPath 1.0表达式是:
"/release/images/image[@type="primary"]/@uri"
可能您只需要修复XPath。
我想以
type="primary
"所在的图像节点为目标,并返回uri
属性的值。
使用此XPath单行表达式:
/*/images/image[@type="primary"]/@uri
这选择了image
元素的名为uri
的属性,该属性的type
属性的字符串值为"primary"
,并且该属性是images
元素的子元素",该元素是XML文档中顶部元素的子节点"。
要只获取属性的值,请使用以下XPath表达式:
string(/*/images/image[@type="primary"]/@uri)
请注意:这是一个纯XPath解决方案,可以与任何W3C兼容XPath的引擎一起使用。
这个怎么样:
$xml = new SimpleXMLElement(file_get_contents('feed.xml'));
$theUriArray = $xml->xpath('/release/images/image[@type="primary"]');
$theUri = $theUriArray[0]->attributes()->uri;
echo($theUri);
虽然我是内置DOMDocument的忠实粉丝,而不是SimpleXML,因此对SimpleXML并不那么熟悉。。。
我认为$xml->xpath('/release/images/image[@type="primary"]')
应该给你一个节点列表,而不是一个节点。
在你的情况下,我希望一个可能的解决方案像一样简单
$nodes = $xml->xpath('/release/images/image[@type="primary"]'); // get matching nodes
$node = reset($nodes); // get first item
$uri = $node->attributes()->uri;
既然您特别提到使用SimpleXML,我建议您尝试查看对$xml->path(...)
的调用结果但为了完整性,这是我使用DOMDocument和DOMXPath(它将工作、保证、测试等等(的方式:
$doc = new DOMDocument('1.0', 'utf8');
$doc->loadXML($yourXMLString);
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('/release/images/image[@type="primary"]');
$theNodeYouWant = $nodes->item(0); // the first node matching the query
$uri = $theNodeYouWant->getAttribute('uri');
这看起来有点冗长,但这主要是因为我包含了这一次的初始化。