2010-10-06 154 views
1

我使用curl以俄语使用utf-8获取页面。如果我回显文字,它显示良好。然后我使用这样的代码与俄语语言的PHP问题

$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但不工作。有任何想法吗?

+0

我不明白你的问题是什么。你会得到什么错误文字? “不起作用”是什么意思? – 2010-10-06 12:34:33

+0

而不是俄语我得到了ÐÑоÑо? – kusanagi 2010-10-06 12:36:13

回答

9

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

 
    $dom = new 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"); 
    .......... 
+0

很棒!!!!!!!!!!!! – kusanagi 2010-10-06 16:08:05

+1

+1 for mb_convert_encoding – 2010-11-17 21:34:27

+0

loadHTML从我的理解中只支持ISO-88591。这就是为什么你必须将所有utf-8字符编码到它们的实体中(这实际上是utf-16实体)。如果你想避免转换,你可以使用支持utf-8的loadXML,但是loadXML对破损的元素非常严格,而且你必须为非关闭元素做很多字符串修复,比如
Gorilla3D 2011-07-12 00:20:25

0

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

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

// taken from http://php.net/manual/en/domdocument.loadhtml.php#95251 
+1

我需要加载html而不是xml,这种方式根本不起作用 – kusanagi 2010-10-06 12:41:35

+0

它就是这样。 HTML基本上是一个具有给定定义的XML文档。你总是可以试试看看它是否有效。 – bisko 2010-10-06 13:19:00

0

mb_convert_encoding($ HTML, 'HTML实体', “UTF-8”);

同样的事情为PHPQuery工作。

P.S.我使用phpQuery :: newDocument($ html);

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