使用PHP从网页获取标题标记的内容

时间:2015-07-10 02:38:20

标签: 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显示它但它什么也没显示。问题是什么?

谢谢。

1 个答案:

答案 0 :(得分: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];