php curl CURLOPT_HEADER和dom

时间:2010-10-05 14:43:46

标签: php dom curl

我有以下代码:

curl_setopt($ch, CURLOPT_URL, $host);
  curl_setopt($ch, CURLOPT_HEADER, 1); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  $html = curl_exec($ch);


  preg_match_all('|Set-Cookie: (.*);|U', $html, $results);  
  $cookies = implode(';', $results[1]);


  $dom = new DOMDocument();
  $dom->loadHTML($html);

在线 $ dom-> loadHTML($ html); 我收到以下错误:

Warning: DOMDocument::loadHTML() [function.DOMDocument-loadHTML]:
Misplaced DOCTYPE declaration in
Entity, line: 12 in
D:\Programs\xampp\xampp\htdocs\ip\megafonmoscow.php
on line 39

Warning: DOMDocument::loadHTML()
[function.DOMDocument-loadHTML]:
htmlParseStartTag: misplaced 
tag in Entity, line: 13 in
D:\Programs\xampp\xampp\htdocs\ip\megafonmoscow.php
on line 39

Warning: DOMDocument::loadHTML()
[function.DOMDocument-loadHTML]:
htmlParseStartTag: misplaced 
tag in Entity, line: 14 in
D:\Programs\xampp\xampp\htdocs\ip\megafonmoscow.php
on line 39

Warning: DOMDocument::loadHTML()
[function.DOMDocument-loadHTML]:
Unexpected end tag : head in Entity,
line: 32 in
D:\Programs\xampp\xampp\htdocs\ip\megafonmoscow.php
on line 39

Warning: DOMDocument::loadHTML()
[function.DOMDocument-loadHTML]:
htmlParseStartTag: misplaced 
tag in Entity, line: 34 in
D:\Programs\xampp\xampp\htdocs\ip\megafonmoscow.php
on line 39

curl_setopt($ch, CURLOPT_HEADER, 1);行是否导致此错误?因为饼干,我需要它。关于如何解决这个问题的任何想法?

2 个答案:

答案 0 :(得分:2)

尝试删除该行,以便它不会返回标题,然后使用get_headers函数在curl请求之后获取它们。

  curl_setopt($ch, CURLOPT_URL, $host);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  $html = curl_exec($ch);
  $headers=get_headers($host, 1);

答案 1 :(得分:2)

mck89方法的替代方法是将标题和正文一起下载,但在尝试解析它之前将其拆分:

$html = curl_exec($ch);

[snip]

$html = preg_replace('/^.*\n\n/s','',$html,1); // strip out everything before & including the double line break between headers and body

$dom = new DOMDocument();
$dom->loadHTML($html);

这会保存HTTP请求,因此需要一定的时间。