PHP& xPath问题 [英] PHP & xPath Question

查看:77
本文介绍了PHP& xPath问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP和xPath爬网到我拥有的网站(只是爬网html而不进入服务器),但是出现此错误:

I'm using PHP and xPath to crawl into a website I own (just crawl the html not going into the server) but I get this error:

可捕获的致命错误:类的对象 DOMNodeList无法转换为 C:\ wamp \ www \ crawler.php中的字符串 第46

Catchable fatal error: Object of class DOMNodeList could not be converted to string in C:\wamp\www\crawler.php on line 46

我已经尝试过仅回显该行以查看得到的内容,但是我会得到相同的错误,也尝试过搜索该错误,但是最后我最终进入了php文档,发现我的示例是与php文档中的完全一样,只是我使用的是HTML而不是XML ...所以我不知道这是怎么回事...这是我的代码...

I already tried echoing just that line to see what I was getting but I would just get the same error also I tried googling for the error but I, in the end, ended up in the php documentation and found out my example is exactly as the one in php documentation except I'm working with an HTML instead of a XML...so I have no idea what's wrong...here's my code...

<?php
$html = file_get_contents('http://miurl.com/mipagina#0');
// create document object model
$dom = new DOMDocument();
// load html into document object model
@$dom->loadHTML($html);
// create domxpath instance
$xPath = new DOMXPath($dom);
// get all elements with a particular id and then loop through and print the href attribute
$elements = $xPath->query("//*[@class='nombrecomplejo']");
if ($elements != null) {
    foreach ($elements as $e) {
      echo parse_str($e);
    } 
}                                                   
?>


修改

实际上是很抱歉,当我评论其他内容时,该行将进行测试...我在这里删除它仍然有错误.

Actually yes sorry that line was to test when I had commented other stuff...I deleted it here still have the error though.

推荐答案

根据文档,则不需要"$elements != null"检查. DOMXPath::query()将始终返回DOMNodeList,尽管它的长度可能为零,这不会混淆foreach循环.

According to the documentation, the "$elements != null" check is unnecessary. DOMXPath::query() will always return a DOMNodeList, though maybe it will be of zero length, which won't confuse the foreach loop.

此外,请注意使用nodeValue属性来获取元素的文本表示形式:

Also, note the use of the nodeValue property to get the element's textual representation:

$elements = $xPath->query("//*[@class='nombrecomplejo']");

foreach ($elements as $e) {
  echo $e->nodeValue;
}

出现错误的原因是,除了字符串以外,您无法将其他任何内容提供给 parse_str() ,您尝试传入DOMElement.

The reason for the error you got is that you can't feed anything other than a string to parse_str(), you tried passing in a DOMElement.

这篇关于PHP&amp; xPath问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆