使用 PHP 从需要身份验证的页面检索 HTML 内容


Retrieving HTML content from a page requiring authentication using PHP

我正在尝试制作一个可以从HTML页面中提取数据的PHP脚本的原型。到目前为止,它适用于不需要身份验证的 html 页面。但是,如何从需要用户先登录的页面中检索内容?

以下是我当前的代码:

<?php
 $url="http://anandtech.com";
 $html = file_get_contents($url);
 $doc = new DOMDocument();
 @$doc->loadHTML($html);
 $xml=simplexml_import_dom($doc);
 $items = $xml->xpath("/html/body/section[@class='content']/section[@class='main_cont']/div[@class='pipeline']/div[@class='pipeline_cont']/ul[1]/li[@class='hide_resp']/a[1]/span[text()]");
 echo '<ul>';
 foreach ($items as $item) {
   echo '<li>' . $item . '</li>';
 }
 echo '</ul>';
?>

如果你的意思是HTTP认证,你可以用curl_init()

  $ch = curl_init();    // initialize curl handle
  curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
  curl_setopt($ch, CURLOPT_TIMEOUT, 4); // times out after 4s
  curl_setopt($ch, CURLOPT_PORT, $port);
  curl_setopt($ch, CURLOPT_USERPWD, 'username:password'); // add POST fields
  $result = curl_exec($ch);

或者您可以通过以下方式发布获取/发布值

  $ch = curl_init();    // initialize curl handle
  curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
  curl_setopt($ch, CURLOPT_TIMEOUT, 4); // times out after 4s
  curl_setopt($ch, CURLOPT_PORT, $port);
  curl_setopt($ch, CURLOPT_POSTFIELDS, 'login='.$username); // add POST fields
  $result = curl_exec($ch);

请参阅 curl_setopt()