domdocument字符集问题

时间:2012-06-01 15:12:54

标签: php domdocument

这个女巫的视频我想获得 og:title

http://www.youtube.com/watch?feature=player_embedded&v=A683kmvRH_8

Php代码

function file_get_contents_curl($url){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $data = curl_exec($ch);
            curl_close($ch);
            return $data;
        }

        $html = file_get_contents_curl($pageurl);

        $doc = new DOMDocument();
        @$doc->loadHTML($html);
        $nodes = $doc->getElementsByTagName('title');

        $titleBackUp = $nodes->item(0)->nodeValue;

        $metas = $doc->getElementsByTagName('meta');

        for ($i = 0; $i < $metas->length; $i++){
            $meta = $metas->item($i);
            if($meta->getAttribute('name') == 'title')
                $title = $meta->getAttribute('content');
        }

标题是Мастило - Връцететиенай-добре[HQ] 我正在

ÐаÑÑило - ÐÑÑÑÐμÑÐμÑиÐμнай-Ð'обÑÐμ[HQ]

我也尝试用

 curl_setopt( $ch, CURLOPT_ENCODING, "UTF-8" );

但它起作用了。

我尝试使用 html_entity_decode ,但无效

1 个答案:

答案 0 :(得分:1)

如果文档本身不包含<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />标记,则会发生这种情况。

您可以尝试以下任一方法:

  1. DomDocument直接从服务器加载HTML(即使用->loadHTMLFile()

  2. 在通过->loadHTML()运行之前,使用上述元标记对文档进行前缀。

  3. 例如,你可以这样做:

    libxml_use_internal_errors(true);
    $doc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . $html);
    libxml_clear_errors();
    

    让libxml知道它应该读取utf-8数据是一种破解......不可能通过->loadHTML()传递该编码。

相关问题