Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/237.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 查找&;打印HTML文档中的第一个div_Php_Html_Dom_Domdocument_Domxpath - Fatal编程技术网

Php 查找&;打印HTML文档中的第一个div

Php 查找&;打印HTML文档中的第一个div,php,html,dom,domdocument,domxpath,Php,Html,Dom,Domdocument,Domxpath,我试图在远程页面中找到第一个div元素,但遇到了困难。以下是我到目前为止的情况: $url = "http://feed2all.eu/watch/193916/1/watch-skysports.html"; $html = file_get_contents($url); $doc = new DOMDocument(); // create DOMDocument libxml_use_internal_errors(true); $doc->validateOnParse = t

我试图在远程页面中找到第一个
div
元素,但遇到了困难。以下是我到目前为止的情况:

$url = "http://feed2all.eu/watch/193916/1/watch-skysports.html";
$html = file_get_contents($url);
$doc = new DOMDocument(); // create DOMDocument
libxml_use_internal_errors(true);

$doc->validateOnParse = true;
$doc->preserveWhiteSpace = false;
$doc->loadHTML($html); // load HTML you can add $html

$xpath = new DOMXpath($doc);
$nodes = $xpath->query( "//div");
foreach( $nodes as $node) {
    echo $node;
}
我还尝试使用:

$divs = $doc->getElementsByTagName('div');
foreach ($divs as $div) {
    echo $div;
}
编辑:如何回显get div的内部html

             $xpath = new DOMXpath($doc);
             $div = $xpath->query("//div[1]")->item(0);
             function get_inner_html( $div ) {
             $innerHTML= '';
             $children = $div->childNodes;
             foreach ($children as $child) {
             $innerHTML .= $child->ownerDocument->saveXML( $child );
              }
             echo $innerHTML;
              }

如果您想使用第一个div,它将提供空白页:

$div = $xpath->query("//div[1]")->item(0);
此外,您不能使用
echo
打印
doElement
。您可以打印它的值:

echo $div->nodeValue;
或者它的属性:

echo $div->getAttribute('foo');

在评论中,您询问了一种获取
div
innerHTML
的方法。下面是一个如何获取
站点的第一个标记的HTML的示例:

$url = 'http://stackoverflow.com/questions/20600265/find-print-the-first-div-in-an-html-document?noredirect=1#comment30824495_20600265';

$doc = new DOMDocument();
@$doc->loadHTML(file_get_contents($url));
$selector = new DOMXPath($doc);

$div = $selector->query('//div[1]')->item(0);
var_dump($doc->saveHTML($div));

请不要在评论中发布源代码。至少对人类来说,这是不可读的。更新问题并添加我对此感到抱歉,现在检查问题中的编辑。你就是那个人!你救了我一天。你需要调用函数:
get\u inner\u html($div)@hek2mgl请用完整代码相应地更新您的答案。