使用 php 从另一个网站清理 html 代码


Cleaning html code from another website using php

我想从这个网站获取一些数据,但正如你在他们的 html 代码中看到的那样,有一些奇怪的东西在不使用 " 和其他一些东西的情况下<TABLE BORDER=0 CELLSPACING=1 CELLPADDING=3 WIDTH=100%>进行,所以当我尝试使用 SimpleXmlElement 解析表时我遇到了错误,我已经使用了一段时间并且在某些网站中运行良好,我正在做这样的事情:

$html = file_get_html('https://secure.tibia.com/community/?subtopic=killstatistics&world=Menera');
$table = $html->find('table', 4);
$xml = new SimpleXmlElement($table);

我得到了一堆错误和东西,那么有没有办法在发送到 SimpleXmlElement 或使用另一种 DOM 类之前清理代码?你们有什么建议?

HTML 代码的问题在于标签属性没有用引号括起来:HTML 中允许使用不带引号的属性,但在 XML 中不允许使用。

如果你不关心属性,你可以继续使用Simple HTML Dom,否则你必须改变HTML解析器。

使用简单 HTML DOM 清理属性:

开始创建一个函数来清除所有节点属性:

function clearAttributes( $node )
{
    foreach( $node->getAllAttributes() as $key => $val )
    {
        $node->$key = Null;
    }
}

然后将该函数应用于<table><tr><td>节点:

clearAttributes( $table );
foreach( $table->find('tr') as $tr )
{
    clearAttributes( $tr );
    foreach( $tr->find( 'td' ) as $td )
    {
        clearAttributes( $td );
    }
}

最后但并非最不重要的一点是:网站HTML包含许多编码字符。如果您不希望在 XML 中看到很多<td>1&#xA0;</td><td>0&#xA0;</td>,则必须在字符串前面加上一个utf-8声明,然后再将其导入 SimpleXml 对象:

$xml = '<?xml version="1.0" encoding="utf-8" ?>'.html_entity_decode( $table );
$xml = new SimpleXmlElement( $xml );

使用 DOMDocument 保留属性:

内置的DOMDocument类比Simple HTML Dom更强大,占用的内存更少。在这种情况下,它将为您格式化原始 HTML。尽管外观如此,但它的使用很简单。

首先,您必须初始化一个DOMDocument对象,设置libxml_use_internal_errors(以禁止在格式错误的HTML上显示大量警告)并加载您的URL:

$dom = new DOMDocument();
libxml_use_internal_errors( 1 );
$dom->loadHTMLfile( 'https://secure.tibia.com/community/?subtopic=killstatistics&world=Menera' );
$dom->formatOutput = True;

然后,您检索所需的<table>

$table = $dom->getElementsByTagName( 'table' )->item(4);

而且,就像Simple HTML Dom示例中一样,您必须在声明前面加上utf-8以避免出现奇怪的字符:

$xml = '<?xml version="1.0" encoding="utf-8" ?>'.$dom->saveHTML( $table );
$xml = new SimpleXmlElement( $xml );

如您所见,将节点检索为 HTML 的DOMDocument语法与 Simple HTML Dom 不同:您需要始终引用 main 对象并指定要打印为参数的节点:

echo $dom->saveHTML();          // print entire HTML document
echo $dom->saveHTML( $node );   // print node $node

编辑:删除 &nbsp; 与 DOMDocument:

要从 HTML 中删除不需要的&#160;,您可以预加载 HTML 并使用 str_replace

更改此行:

$dom->loadHTMLfile( 'https://secure.tibia.com/community/?subtopic=killstatistics&world=Menera' );

有了这个:

$data = file_get_contents( 'https://secure.tibia.com/community/?subtopic=killstatistics&world=Menera' );
$data = str_replace( '&#160;', '', $data );
$dom->loadHTML( $data );