我编写此代码来解析craigslist
网站的标题。
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://craigslist.org/about/sites");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
$cl = curl_exec($ch);
$dom = new DOMDocument('1.0');
@$dom->loadHTML($cl);
$title = $dom -> getElementById("logo");
echo $title->nodeValue;
?>
但它显示错误:
Notice: Trying to get property of non-object in C:\xampp\htdocs\products\index.php on line 13
我在哪里搞砸了?
答案 0 :(得分:1)
这有效:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://craigslist.org/about/sites");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
$cl = curl_exec($ch);
$dom = new DOMDocument('1.0');
@$dom->loadHTML($cl);
$title = $dom -> getElementById("logo");
echo $title->nodeValue;
我使用curl_getinfo
和您的初始代码来查看有关HTTP响应的更多信息,并获得302重定向作为HTTP响应代码。您可以通过设置CURLOPT_FOLLOWLOCATION
选项跟随cURL重定向。