使用 curl 加载头部内容


Load head content using curl

我想仅使用 curl 加载头部的内容,目前我正在使用

<?php 
$url="www.facebook.com";
$title='';$keywords='';$description='';
    $ch = curl_init();
$timeout=5;
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, 'http://'.$url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt ($ch, CURLOPT_TIMEOUT,0);
    $html = curl_exec($ch);
    curl_close($ch);
echo htmlspecialchars($html);//gives the complete source.Why?
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
$metas = $doc->getElementsByTagName('meta');
if($nodes->length>0)$title = $nodes->item(0)->nodeValue;
for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
}
echo $title. '<br/>';
echo "&nbsp;&nbsp;&nbsp;&nbsp;$description". '<br/>';
echo "&nbsp;&nbsp;&nbsp;&nbsp;$keywords";
?>

此代码返回 url 的完整代码,但我只想要头部。不要将其与我之前的问题联系起来,因为这里没有必要使用 curlopt_writefunction()

尽管名称相似,但HEADER与html <head>不对应,BODY也不对应html <body>CURLOPT_HEADER表示在返回值中包含 http 标头。 CURLOPT_NOBODY意味着不要在返回值中包含 http 有效负载(具有 content-type:text/html 的 http 响应的有效负载将是整个 HTML 文档)。

CURLOPT_HEADER应该是 TRUE,而不是 0

CURLOPT_NOBODY应该是真的

curl_setopt($ch, CURLOPT_NOBODY, TRUE);