2014-09-27 32 views
2

我這裏有一些問題,簡單的HTML DOM和捲曲的錯誤

我的代碼是:

<?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行的非對象

+0

'include_once( 「simple_html_dom.php」);'請問這個文件做 – Hitesh 2014-09-27 20:18:11

回答

1

您不能在非對象上使用成員函數。在這種情況下,您不能使用$element的成員函數find這是一個string

curl_exec文檔:

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

的結果是你試圖讓這是一個STRING

嘗試使用var_dump,你會看到頁面的html內容由你自己。

所以我想你想使用的DOM extensionDOMXpath class和做類似:

$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的。

+0

非常感謝... – 2014-09-27 20:34:25

+0

@MasoudHB你是開山鼻祖,很高興它幫助。 – 2014-09-27 20:35:49

+0

不錯的答案...... – Hitesh 2014-09-27 20:45:14

1
  • 請嘗試瞭解面向對象的基本知識。
  • 你將不得不實例化一個simple_html_dom對象來調用它的方法。
  • $result=curl_exec($curl_handle); $html = new simple_html_dom(); $html->load($result);

更換$html = curl_exec($curl_handle);及以上的這部分移動include_once("simple_html_dom.php");

+0

非常感謝... – 2014-09-27 20:33:39

+0

$ tillz非常感謝您的簡單和簡單的解決方案。 – 2016-04-20 12:39:28

1
<?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