【问题标题】:Getting whole HTML element with PHP使用 PHP 获取整个 HTML 元素
【发布时间】:2016-02-24 09:37:32
【问题描述】:

我想获取代表 1 个列表的整个元素 <article>,但它不起作用。有人可以帮帮我吗?

包含图片+标题+链接+描述

<?php

$url = 'http://www.polkmugshot.com/';
$content = file_get_contents($url);
$first_step = explode( '<article>' , $content );
$second_step = explode("</article>" , $first_step[3] );

echo $second_step[0];
?>

【问题讨论】:

  • 我几乎不认为客户端小提琴能够执行 PHP 代码..
  • 我不太明白你想说什么

标签: php regex curl web-scraping file-get-contents


【解决方案1】:

对于此类请求,您绝对应该使用 curl。

function curl_download($url){
  // is cURL installed?
  if (!function_exists('curl_init')){
    die('cURL is not installed!');
  }

  $ch = curl_init();

  // URL to download
  curl_setopt($ch, CURLOPT_URL, $url);

  // User agent
  curl_setopt($ch, CURLOPT_USERAGENT, "Set your user agent here...");

  // Include header in result? (0 = yes, 1 = no)
  curl_setopt($ch, CURLOPT_HEADER, 0);

  // Should cURL return or print out the data? (true = retu rn, false = print)
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Timeout in seconds
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);

  // Download the given URL, and return output
  $output = curl_exec($ch);

  // Close the cURL resource, and free system resources
  curl_close($ch);

  return $output;
}

为您的问题提供最佳结果。结合HTML Dom Parser

像这样使用它:

// Find all images 
foreach($output->find('img') as $element) 
       echo $element->src . '<br>';

// Find all links 
foreach($output->find('a') as $element) 
       echo $element->href . '<br>';

祝你好运!

【讨论】:

  • 我什至会选择 SimpleXML(已经内置),不过 +1 建议 curl()
  • 各位认真的,使用 DOMDocument
【解决方案2】:

我不确定我是否正确,但我想你需要一个 PHP DOM 解析器。我建议this one (这是一个很棒的用于解析 HTML 代码的 PHP 库)

您还可以像这样获得整个 HTML 代码:

$url = 'http://www.polkmugshot.com/';
$html = file_get_html($url);
echo $html;

【讨论】:

    【解决方案3】:

    可能更好的方法是解析文档并在之后对其运行一些 xpath 查询,如下所示:

    $url = 'http://www.polkmugshot.com/';
    $xml = simplexml_load_file($url);
    
    $articles = $xml->xpath("//articles");
    foreach ($articles as $article) {
        // do sth. useful here
    }
    

    在此处了解SimpleXML

    【讨论】:

      【解决方案4】:

      使用 DOMDocument 提取文章。工作示例:

      <?php
      $url = 'http://www.polkmugshot.com/';
      $content = file_get_contents($url);
      $domd=@DOMDocument::loadHTML($content);
      foreach($domd->getElementsByTagName("article") as $article){
          var_dump($domd->saveHTML($article));
      }
      

      正如@Guns 所指出的,您最好使用 curl,原因如下:

      1:如果 php.ini 中的 allow_url_fopen 未设置为 true,file_get_contents 将失败

      2: 直到 php 5.5.0(那里的某个地方),file_get_contents 一直从连接读取,直到连接实际关闭,对于许多服务器来说,在发送所有内容后可能需要几秒钟,而 curl 只会读取直到它达到内容长度的 HTTP 标头,这使得传输速度更快(幸运的是,此问题已修复)

      3:curl 支持 gzip 和 deflate 压缩传输,这再次使传输速度更快(当内容可压缩时,例如 html),而 file_get_contents 将始终传输纯文本

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-06
        • 2012-03-21
        • 2014-04-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多