SimpleXML、关联数组和 XPath
我有一个关于 xpath 和数组的问题。 我想知道是否可以在某些 simpleXML 上使用 xpath 并让它返回节点名称及其值的关联数组。 例如,假设我有以下 XML:
<element1 page="1">blah</element1>
<element2 page="1">blah blah</element2>
<element3 page="2">blah</element3>
<element4 page="3">blah blah</element4>
现在,如果我要执行 $xml->xpath('//node()[@page="1"]');
那么它会返回一个如下所示的数组:
array( 0 => 'blah' , 1 => 'blah blah' );
是否可以得到一个类似于下面的数组?
array( element1 => 'blah' , element2 => 'blah blah' );
谢谢您的帮助!
I have a question about xpath and arrays. What I was wondering was if it is possible to use xpath on some simpleXML and have it return an associative array of node names and their values. For example, say I have the following XML:
<element1 page="1">blah</element1>
<element2 page="1">blah blah</element2>
<element3 page="2">blah</element3>
<element4 page="3">blah blah</element4>
Now if I were to go $xml->xpath('//node()[@page="1"]');
then it would return an array like the following:
array( 0 => 'blah' , 1 => 'blah blah' );
Is it possible to get an array similar to the one below?
array( element1 => 'blah' , element2 => 'blah blah' );
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为你可以将其获取到那种数组中(你需要告诉 PHP 放什么标签、子节点、属性等),但你可以使用 DOMXPath 类,它为您提供一个 DOMNodeList 对象:
I don't think you can fetch that into that kind of array (you would need to tell PHP what tags, child nodes, attributes, etc to put there), but you can fetch DOMNode elements using the DOMXPath class, which gives you a DOMNodeList object:
对于简单的 XML,数组并不完全像您提到的那样,它更像是:
因为您有一个 SimpleXML 对象而不是文字字符串,您仍然可以访问完整的 SimpleXML 文档:
或者更接近您的问题
,如果您对所有事情都着迷你可以使用 DOM 属性,然后你可以执行以下操作:
For simple XML the array is not exactly as you mentioned it's more like:
because you have a SimpleXML object and not a literal string you still have access to the full SimpleXML document:
or closer to your question
and if you are smitten with all the things you can do with DOM properties then you can do something like: