2

我想从网页中提取几个表格并在我的页面中显示它们

我打算使用正则表达式来提取它们,但后来我看到了 DOMDocument 类,我在 stackoverflow 中查看它看起来更干净,似乎所有的问题都是关于获取内部文本或使用循环来获取元素的内部节点。我现在想知道如何通过它的 id 提取和打印 html 元素。

$html = file_get_contents("www.site.com");
$xml = new DOMDocument();
$xml->loadHTML($html);
$xpath = new DOMXPath($xml);
$table =$xpath->query("//*[@id='myid']");
$table->saveHTML(); // this obviously doesn't work

如何在我的页面上将 $table 显示或回显为实际的 html 表格?

4

2 回答 2

7

首先,DOMDocument有一个getElementById()方法,所以你的 XPath 是不必要的——尽管我怀疑它在下面是如何工作的。

其次,为了获得标记片段而不是整个文档,您使用DOMNode::C41N(),因此您的代码如下所示:

<?php

    // Load the HTML into a DOMDocument
    // Don't forget you could just pass the URL to loadHTML()
    $html = file_get_contents("www.site.com");
    $dom = new DOMDocument('1.0');
    $dom->loadHTML($html);

    // Get the target element
    $element = $dom->getElementById('myid');

    // Get the HTML as a string
    $string = $element->C14N();

请参阅一个工作示例

于 2012-06-27T12:20:02.937 回答
1

您可以使用 DOMElement::C14N() 来获取 DOMElement 的规范化 HTML(XML) 表示,或者如果您喜欢更多控制以便可以过滤某些元素和属性,您可以使用如下内容:

function toHTML($nodeList, $tagsToStrip=array('script','object','noscript','form','style'),$attributesToSkip=array('on*')) {
$html = '';
foreach($nodeList as $subIndex => $values) {
    if(!in_array(strtolower($values->nodeName), $tagsToStrip)) {
        if(substr($values->nodeName,0,1) != '#') {
            $html .= ' <'.$values->nodeName;
            if($values->attributes) {
                for($i=0;$values->attributes->item($i);$i++) {
                    if( !in_array( strtolower($values->attributes->item($i)->nodeName) , $attributesToSkip ) && (in_array('on*',$attributesToSkip) && substr( strtolower($values->attributes->item($i)->nodeName) ,0 , 2) != 'on') ) {
                        $vvv = $values->attributes->item($i)->nodeValue;
                        if( in_array( strtolower($values->attributes->item($i)->nodeName) , array('src','href') ) ) {
                            $vvv = resolve_href( $this->url , $vvv );
                        }
                        $html .= ' '.$values->attributes->item($i)->nodeName.'="'.$vvv.'"';
                    }
                }
            }
            if(in_array(strtolower($values->nodeName), array('br','img'))) {
                $html .= ' />';
            } else {
                $html .= '> ';
                if(!$values->firstChild) {
                    $html .= htmlspecialchars( $values->textContent , ENT_COMPAT , 'UTF-8' , true );
                } else {
                    $html .= toHTML($values->childNodes,$tagsToStrip,$attributesToSkip);
                }
                $html .= ' </'.$values->nodeName.'> '; 
            }
        } elseif(substr($values->nodeName,1,1) == 't') {
            $inner = htmlspecialchars( $values->textContent , ENT_COMPAT , 'UTF-8' , true );
            $html .= $inner;
        }
    }
}
return $html;
}

echo toHTML($table);
于 2012-06-27T12:35:28.653 回答