抓取页面时DOMDocument编码问题

时间:2013-08-13 14:39:35

标签: php

我正在抓取谷歌播放链接以获取某些信息以检索应用名称。

问题是某些应用程序返回了不可读的字符。

        $div2 = $div->getElementsByTagName("div");
        if ($div2->length)
        {
            $gpAppName = DOMinnerHTML($div2->item(0));
            $counter++;
            if(checkIfMaxedOutAndReturn($counter)){
                buildObjAndReturn($gpIcon,$gpBg,$gpAppName,$gpBtnLink);
            }
        }
        function DOMinnerHTML($element)
        {
            $innerHTML = "";
            $children = $element->childNodes;
            foreach ($children as $child)
            {
                $tmp_dom = new DOMDocument('1.0','UTF-8');
                $tmp_dom->appendChild($tmp_dom->importNode($child, true));
                $innerHTML.=trim($tmp_dom->saveHTML());
            }
            return $innerHTML;
        }

在废弃页面时:https://play.google.com/store/apps/details?id=com.vascogames.TransportTruck,您在此处看到的代码将刮取应用程序名称“卡车司机 - 货物交付”,但代码返回“卡车司机 - 货物交付”

1 个答案:

答案 0 :(得分:0)

这很棘手,底层的libxml2库会查找指定编码的HTML标记,而Google Play页面则不会提供任何编码。这是一个快速解决方案,在解析之前将元标记注入源:

<?php

$url = 'https://play.google.com/store/apps/details?id=com.vascogames.TransportTruck';

$source = file_get_contents($url);
$source = str_replace(
  '<head>',
  '<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">',
  $source
);

$dom = new DOMDocument;
@$dom->loadHTML($source);

$divs = $dom->getElementsByTagName('div');

foreach ($divs as $div) {
  if ($div->getAttribute('class') === 'document-title') {
    echo trim($div->textContent);
    echo "\n";
  }
}