Php 获取远程页面的源代码,然后根据其id仅显示一个div

Php 获取远程页面的源代码,然后根据其id仅显示一个div,php,file-get-contents,Php,File Get Contents,与当前标题中描述的完全一样,我的代码是: <?php $url = "remotesite.com/page1.html"; $html = file_get_contents($url); $doc = new DOMDocument(); // create DOMDocument libxml_use_internal_errors(true); $doc->loadHTML($html); // load HTML you can ad

与当前标题中描述的完全一样,我的代码是:

<?php
    $url = "remotesite.com/page1.html";
    $html = file_get_contents($url);
    $doc = new DOMDocument(); // create DOMDocument
    libxml_use_internal_errors(true);
    $doc->loadHTML($html); // load HTML you can add $html

    $elements = $doc->getElementsByTagName('div');

?>
loadHTML($html);//加载HTML您可以添加$HTML
$elements=$doc->getElementsByTagName('div');
?>

我的编码技能非常基础,因此在这一点上我迷路了,不知道如何只显示id为mydiv的div。如果您使用PHP 5.3.6或更高版本,您可以执行以下操作:

$url = "remotesite.com/page1.html";
$html = file_get_contents($url);
$doc = new DOMDocument(); // create DOMDocument
libxml_use_internal_errors(true);
$doc->loadHTML($html); // load HTML you can add $html
$testElement = $doc->getElementById('divIDName');
echo $doc->saveHTML($testElement);

如果您使用的是较低版本,我相信在找到带有getElementById的Dom节点后,您需要将其复制到一个新的DomDocument对象中

$elementDoc = new DOMDocument();
$cloned = $testElement->cloneNode(TRUE);
$elementDoc->appendChild($elementDoc->importNode($cloned,TRUE));
echo $elementDoc->saveHTML();

感谢您的帮助,但是在您的第一个代码中,变量
$levi
未定义,代码不工作,是的,我有PHP5.4.7Oh,对此表示抱歉。我一直在使用虚拟变量进行测试,但没有更新它。那$levi var应该是$testElement。