如何检索外部​​php站点返回的html元素?

时间:2015-02-20 11:37:41

标签: php html

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

返回以下html元素

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

如何检索数据&#34; ABC&#34;所以我可以使用这些数据在我自己的网站上显示?

4 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分:0)

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()?

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

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代替匹配。