PHP Xpath 提取属性 name=“author”的节点的值
我正在尝试解析一些 XML 数据以获取某个属性的值 - 具体来说,我想找到作者。下面是一个非常精简但有效的示例。 R
节点重复多次。
<GSP VER="3.2">
<RES SN="1" EN="10">
<R N="4" MIME="application/pdf">
<Label>_cse_rvfaxixpaw0</Label>
<PageMap>
<DataObject type="metatags">
<Attribute name="creationdate" value="D:20021024104222Z"/>
<Attribute name="author" value="Diana Van Winkle"/>
</DataObject>
</PageMap>
</R>
</RES>
</GSP>
目前我这样做:
$XML = simplexml_load_string($XMLResult);
$XMLResults = $XML->xpath('/GSP/RES/R');
foreach($XMLResults as $Result) {
$Label = $Result->Label;
$Author = ""; // <-- How do I get this?
}
有人可以向我解释一下如何提取“作者”属性吗?作者属性最多出现 1 次,但也可能根本不出现(我可以自己处理)
I'm trying to parse some XML data to get the value of a certain attribute - Specifically, I want to find the author. Below is a very cut-down but valid example. The R
node is repeated multiple times.
<GSP VER="3.2">
<RES SN="1" EN="10">
<R N="4" MIME="application/pdf">
<Label>_cse_rvfaxixpaw0</Label>
<PageMap>
<DataObject type="metatags">
<Attribute name="creationdate" value="D:20021024104222Z"/>
<Attribute name="author" value="Diana Van Winkle"/>
</DataObject>
</PageMap>
</R>
</RES>
</GSP>
Currently I do:
$XML = simplexml_load_string($XMLResult);
$XMLResults = $XML->xpath('/GSP/RES/R');
foreach($XMLResults as $Result) {
$Label = $Result->Label;
$Author = ""; // <-- How do I get this?
}
Can someone please explain to me how I can pull out the "author" attribute? The author attribute will be present a maximum of 1 times but may not be present at all (I can handle that myself)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是解决方案。基本上,您可以对结果节点进行 XPath 调用,以获取名称属性等于作者的所有属性元素。
然后检查并确保结果返回,如果返回,则它将是索引[0],因为 XPath 调用返回结果数组。然后使用attributes()函数获取属性的关联数组,最终得到你想要的值。
Here is the solution. Basically you can make an XPath call off the result node to get all attribute elements with the name attribute equal to author.
Then you check and make sure a result came back, and if it did, it will be index[0] since XPath calls return an array of results. Then you use the
attributes()
function to get an associate array of the attribute, finally getting the value you want.