4

我使用 curl 获取带有俄语的 utf-8 页面。如果我回显文本,则显示良好。然后我使用这样的代码

$dom = new domDocument; 

        /*** load the html into the object ***/ 
        @$dom->loadHTML($html); 

        /*** discard white space ***/ 
        $dom->preserveWhiteSpace = false; 

        /*** the table by its tag name ***/ 
        $tables = $dom->getElementsByTagName('table'); 

        /*** get all rows from the table ***/ 
        $rows = $tables->item(0)->getElementsByTagName('tr'); 

        /*** loop over the table rows ***/ 
        for ($i = 0; $i <= 5; $i++)
        { 
            /*** get each column by tag name ***/ 
            $cols = $rows->item($i)->getElementsByTagName('td'); 

            echo $cols->item(2)->nodeValue; 

            echo '<hr />'; 
        } 

$html 包含俄语文本。在它之后echo $cols->item(2)->nodeValue; 显示错误文本,而不是俄语。我尝试 iconv 但不起作用。有任何想法吗?

4

3 回答 3

13

我建议在加载 UTF-8 页面之前使用mb_convert_encoding 。

    $dom = 新的 DomDocument();   
    $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
    @$dom->loadHTML($html);

或者你可以试试这个

    $dom = new DomDocument('1.0', 'UTF-8');
    @$dom->loadHTML($html);
    $dom->preserveWhiteSpace = false;
    …………
    echo html_entity_decode($cols->item(2)->nodeValue,ENT_QUOTES,"UTF-8");
    …………
于 2010-10-06T13:01:27.507 回答
1

DOM 无法识别 HTML 的编码。您可以尝试以下方法:

$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="UTF-8">' . $html);

// taken from http://php.net/manual/en/domdocument.loadhtml.php#95251
于 2010-10-06T12:38:44.190 回答
0

mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");

同样的事情也适用于 PHPQuery。

PS 我使用 phpQuery::newDocument($html);

而不是 $dom->loadHTML($html);

于 2014-04-09T10:47:17.400 回答