【问题标题】:How to get the HTML of from an URL in PHP?如何从 PHP 中的 URL 获取 HTML?
【发布时间】:2015-11-18 22:33:39
【问题描述】:

我想要来自 URL 的 HTML 代码。

实际上,我想从一个 URL 的数据中跟踪内容。

1. blog titile
2. blog image
3. blod posted date
4. blog description or actual blog text

我尝试了下面的代码,但没有成功。

<?php
  $c = curl_init('http://54.174.50.242/blog/');
    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt(... other options you want...)

    $html = curl_exec($c);

    if (curl_error($c))
        die(curl_error($c));

    // Get the status code
    $status = curl_getinfo($c, CURLINFO_HTTP_CODE);

    curl_close($c);

    echo "Status :".$status; die;
?>

请帮我从 URL(http://54.174.50.242/blog/) 获取必要的数据。

提前致谢。

【问题讨论】:

标签: php url curl file-get-contents html-entities


【解决方案1】:

您应该使用 Simple HTML Parser 。并使用提取html $html = @file_get_html($url);foreach($html-&gt;find('article') as element) { $title = $dom-&gt;find('h2',0)-&gt;plaintext; .... } 我也在用这个,希望它有效。

【讨论】:

    【解决方案2】:

    你已经成功了一半。您的 curl 请求正在运行,并且 $html 变量包含博客页面源代码。现在您需要从 html 字符串中提取所需的数据。一种方法是使用 DOMDocument 类。

    你可以从这里开始:

    $c = curl_init('http://54.174.50.242/blog/');
    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    $html = curl_exec($c);
    
    $dom = new DOMDocument;
    
    // disable errors on invalid html
    libxml_use_internal_errors(true);
    
    $dom->loadHTML($html);
    
    $list = $dom->getElementsByTagName('title');
    $title = $list->length ? $list->item(0)->textContent : '';
    
    // and so on ...
    

    您还可以通过在 DOMDocument 类上使用方法 loadHTMLFile 来简化它,这样您就不必担心所有 curl 代码样板:

    $dom = new DOMDocument;
    
    // disable errors on invalid html
    libxml_use_internal_errors(true);
    
    $dom->loadHTMLFile('http://54.174.50.242/blog/');
    
    $list = $dom->getElementsByTagName('title');
    $title = $list->length ? $list->item(0)->textContent : '';
    echo $title;
    
    // and so on ...
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 2013-11-27
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      相关资源
      最近更新 更多