我这里有一些问题,
我的代码是:
<?php
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'http://www.website.org');
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'name');
$html = curl_exec($curl_handle);
curl_close($curl_handle);
include_once("simple_html_dom.php");
$element= $html->find("div[class=something]");
echo $element;
?>
我得到了这个错误:致命错误:在第10行的非对象上调用成员函数find()
不能在非对象上使用成员函数。在这种情况下,不能在作为string
的$element
上使用成员函数find
。
来自curl_exec的文档:
返回值
成功时返回TRUE,失败时返回FALSE。但是,如果设置了CURLOPT_RETURNTTRANSFER选项,它将在成功时返回结果,在失败时返回FALSE。
结果是您试图获得的页面的html内容,即STRING
尝试使用var_dump,您将自己看到。
因此,我猜您希望使用DOM扩展和DOMXpath类,并执行以下操作:
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'http://www.website.org');
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'name');
$html = curl_exec($curl_handle);
curl_close($curl_handle);
$encodeHtml = utf8_encode(html_entity_decode($html));
$dom = new DOMDocument;
$dom->loadXML($encodeHtml);
$xpath = new DOMXPath($dom);
$res = $xpath->query($Path);
$Path
是您试图回显的元素的xpath。
- 请试着理解面向对象的基本知识
- 您必须实例化一个simple_html_dom对象才能调用其上的方法
- 请将
$html = curl_exec($curl_handle);
替换为$result=curl_exec($curl_handle); $html = new simple_html_dom(); $html->load($result);
并将CCD_ 8移动到该部分上方。
<?php
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'http://www.google.com');
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'name');
$html = curl_exec($curl_handle);
curl_close($curl_handle);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$mytag = $doc->getElementsByTagName('div');
foreach ($mytag as $value) {
//echo $value->nodeValue, PHP_EOL;
//echo $value->getAttribute('class'), PHP_EOL;
if($value->getAttribute('class') == "someclass"){
//do something
}
?>
http://php.net/manual/en/domdocument.getelementsbytagname.php