【问题标题】:How to retrieve html elements returned by an external php site?如何检索外部​​ php 站点返回的 html 元素?
【发布时间】:2015-12-26 00:53:13
【问题描述】:

有一个外部网站http://example.com/phprender.php

返回以下html元素

<div id="phprender">
  <p id='101'>ABC</p>
  <p id='102'>Hello World!</p>
</div>

如何检索数据“ABC”,以便可以使用该数据在我自己的网站上显示?

【问题讨论】:

  • 使用file_get_contents下载HTML,使用DOMDocument解析。
  • 如果从特定站点抓取内容是合法的,那么您应该研究 PHP 中的 HTML 解析器,尤其是 DOMDocument

标签: php html


【解决方案1】:

使用 DomDocument 解析 HTML,并使用 DOMXpath 检索:

    $url="http://example.com/phprender.php";
    $doc = new DOMDocument();
    $content=file_get_contents($url);
    $doc->loadHTML($content);
    $xpath = new DOMXpath($doc);

    $elements=$xpath->query("//p[@id='101']");
    if (!is_null($elements))
    foreach ($elements as $ele) {
         echo $ele->nodeValue;
    }

【讨论】:

    【解决方案2】:

    如果您想使用 javascript 方法,请确保外部站点已禁用 cors。你可以阅读here。然后使用 jquery 加载它:

    $("#content").load("services.html #IdOfelementToLoad");
    

    你可以在你的情况下使用#101。

    【讨论】:

    • 我无权访问外部网站。
    • 那么您可能想使用 php 方法。尝试 davidwalsh.name/curl-download 然后 substr $returned_content 只得到你需要的东西。
    【解决方案3】:

    file_get_contents

    <?php
    $html = file_get_contents('http://example.com/phprender.php');
    echo $html;
    ?>
    


    客户方式
    Is there a JavaScript way to do file_get_contents()?

    【讨论】:

    【解决方案4】:

    PHP 解决方案

    您可以使用 file_get_contents 并像这样执行正则表达式匹配:

    preg_match('/<p.*>(.*)<\/p>/i',file_get_contents('http://example.com/phprender.php'), $matches);
    print_r($matches[1]);
    

    jQuery 解决方案

    使用 JQuery,您可以使用 get 来检索远程 html,如下所示:

    $.get( "http://example.com/phprender.php", function( data ) {
      $( ".result" ).html( data );
      var myMatch = data.match(/<p.*>(.*)<\/p>/i);
    });
    

    或者使用 DOM 代替匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      相关资源
      最近更新 更多