Php Experts,
Этот скрипт работает:
include('simple_html_dom.php');
$html = file_get_html('http://google.com');
//to fetch all hyperlinks from a webpage
$links = array();
foreach($html->find('a') as $a) {
$links[] = $a->href;
}
print_r($links);
echo "<br />";
//to fetch all images from a webpage
$images = array();
foreach($html->find('img') as $img) {
$images[] = $img->src;
}
print_r($images);
echo "<br />";
//to find h1 headers from a webpage
$headlines = array();
foreach($html->find('h1') as $header) {
$headlines[] = $header->plaintext;
}
print_r($headlines);
echo "<br />";
?>
Я не получаю ошибки, что "find" не распознан.Но почему я получаю эту ошибку на следующих моих модификациях?
<?php
/* FINDING HTML ELEMENTS BASED ON THEIR TAG NAMES
Suppose you wanted to find each and every link on a webpage.
We will be using “find” function to extract this information from the
object. Here’s how to do it using Simple HTML DOM Parser :
*/
include('simple_html_dom.php');
$url = 'https://www.yahoo.com';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$html = curl_exec($curl);
//to fetch all hyperlinks from a webpage
$links = array();
foreach($html->find('a') as $a) {
$links[] = $a->href;
}
print_r($links);
echo "<br />";
?>
Я получаю ошибку: Неустранимая ошибка: ошибка Uncaught: вызов функции-члена find () для строки в C: \ xampp \htdocs \ cURL \ crawler.php: 24 Трассировка стека: # 0 {main}, брошенный в C: \ xampp \ htdocs \ cURL \ crawler.php в строке 24
Странно!Почему я не получаю ту же ошибку в отношении «поиска» в первом работающем скрипте?Очень странно!Оба сценария практически одинаковы.В моей модифицированной версии я просто заменил «$ html = file_get_html ('');»;с курлом.Смотрите сами.
Файл simple_html_dom.php можно скачать здесь: https://sourceforge.net/projects/simplehtmldom/files/ Я поместил этот файл DOM в тот же каталог, что и файл скрипта.Это означает, что я только что заменил:
//$html = file_get_html('http://nimishprabhu.com');
на:
$url = 'https://www.yahoo.com';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$html = curl_exec($curl);
Это все!
1-е РЕДАКТИРОВАНИЕ: код u_mulder работает на некоторых URL, но не наYahoo.Почему это?
$url = 'https://www.yahoo.com';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$response_string = curl_exec($curl);
$html = str_get_html($response_string);
//to fetch all hyperlinks from a webpage
$links = array();
foreach($html->find('a') as $a) {
$links[] = $a->href;
}
print_r($links);
echo "<br />";