2015-07-10 97 views
0

嗨,从PHP的网页获取标题标签的内容

我想从我的网站内的页面获取标题标记的内容。但是,file_get_contents被禁用,所以看起来像cURL是我唯一的选择。这就是我想:

$domain="http://example.com"; 
ob_start(); 
$curl_handle=curl_init(); 
curl_setopt($curl_handle, CURLOPT_URL, $domain. '/blog/index.php?page=4'); 
$getit = curl_exec($curl_handle); 
curl_close($curl_handle); 
ob_end_clean(); 
preg_match("/<title>(.*)<\/title>/i", $getit, $matches); 
$title= $matches[1]; 

我不得不使用ob_start和清洁,因为否则称为页面嵌入到我最后的HMTL代码,我不需要。我只需要获取标签值并让$ title显示它,但它什么都不显示。这里有什么问题?

谢谢。

+0

做尝试打印$ GETIT?或$匹配?并看看结果是什么 –

+1

是的,getit的结果是“1”,但$匹配只能打印“数组”。 –

+0

完整的HTML你能看到我的标题? –

回答

1

使用

curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true); 

最后的代码应该是

$domain="http://example.com"; 
ob_start(); 
$curl_handle=curl_init(); 
curl_setopt($curl_handle, CURLOPT_URL, $domain. '/blog/index.php?page=4'); 
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true); 
$getit = curl_exec($curl_handle); 
curl_close($curl_handle); 
ob_end_clean(); 
preg_match("/<title>(.*)<\/title>/i", $getit, $matches); 
$title= $matches[1]; 
+0

谢谢,我错过了那一行。但是,似乎ob_start()也不是必需的。还有一个问题,被调用页面的编码与实际页面不同。是否有可能改变编码? –

+0

没关系,我明白了!谢谢。 –

+0

嘿尝试使用curl_setopt($ curl_handle,CURLOPT_ENCODING,“”); –