xpath没有返回值
当我使用以下代码使用 var_dump
时,我可以使用 xpath 提取必要的信息。当我尝试添加 foreach 循环以返回所有 ["href"]
值时,我得到一个空白页,有什么想法我搞砸了吗?
$dom = new DOMDocument();
@$dom->loadHTML($source);
$xml = simplexml_import_dom($dom);
$rss = $xml->xpath("/html/body//a[@class='highzoom1']");
$links = $rss->href;
foreach ($links as $link){
echo $link;
}
这是信息数组。
array(96) {
[0]=>
object(SimpleXMLElement)#3 (2) {
["@attributes"]=>
array(2) {
["href"]=>
string(49) "/p/18351/test1.html"
["class"]=>
string(10) "highzoom1"
}
[0]=>
string(36) ""test1"
}
[1]=>
object(SimpleXMLElement)#4 (2) {
["@attributes"]=>
array(2) {
["href"]=>
string(43) "/p/18351/test2.html"
["class"]=>
string(10) "highzoom1"
}
[0]=>
string(30) ""test2"
}
[2]=>
object(SimpleXMLElement)#5 (2) {
["@attributes"]=>
array(2) {
["href"]=>
string(48) "/p/18351/test3.html"
["class"]=>
string(10) "highzoom1"
}
[0]=>
string(35) ""test3"
}
I am able to pull the necessary information using xpath, when I use var_dump
using the following code. When I try to add a foreach loop to return all ["href"]
values i get a blank page any ideas where I am messing up?
$dom = new DOMDocument();
@$dom->loadHTML($source);
$xml = simplexml_import_dom($dom);
$rss = $xml->xpath("/html/body//a[@class='highzoom1']");
$links = $rss->href;
foreach ($links as $link){
echo $link;
}
Here is the array of information.
array(96) {
[0]=>
object(SimpleXMLElement)#3 (2) {
["@attributes"]=>
array(2) {
["href"]=>
string(49) "/p/18351/test1.html"
["class"]=>
string(10) "highzoom1"
}
[0]=>
string(36) ""test1"
}
[1]=>
object(SimpleXMLElement)#4 (2) {
["@attributes"]=>
array(2) {
["href"]=>
string(43) "/p/18351/test2.html"
["class"]=>
string(10) "highzoom1"
}
[0]=>
string(30) ""test2"
}
[2]=>
object(SimpleXMLElement)#5 (2) {
["@attributes"]=>
array(2) {
["href"]=>
string(48) "/p/18351/test3.html"
["class"]=>
string(10) "highzoom1"
}
[0]=>
string(35) ""test3"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代替:
使用:
您使用的原始 XPath 表达式(上面的第一个)选择 XML 文档中的任何
a
元素,其值class
属性是'highzoom1'
并且(a
元素)是body
的后代,而body
是XML 文档中顶部元素(名为html
)的子元素。但是,您想要选择这些
a
元素的href
属性,而不是a
元素本身。上面的第二个 XPath 表达式精确选择这些
a
元素的href
属性。Instead of:
use:
The original XPath expression (the first above) you are using selects any
a
element in the XML document the value of whoseclass
atribute is'highzoom1'
and that (thea
element) is a descendent of abody
that is a child of the top element (namedhtml
) in the XML document.However, you want to select the
href
attributes of thesea
elements -- not thea
elements themselves.The second XPath expression above select exactly the
href
attributes of thesea
elements.永远不会工作,因为 $rss 是一个 DOMNodeList 对象,并且没有 href 属性。相反,您需要这样做:
或者您可以直接将 $rss 作为数组寻址:
will never work, as $rss is a DOMNodeList object, and won't have an href attribute. Instead, you'd want to do this:
Or you can address $rss as an array directly: