【问题标题】:PHP- HTML parsing :: How can be taken charset value of webpage with simple html dom parser?PHP- HTML 解析 :: 如何使用简单的 html dom 解析器获取网页的字符集值?
【发布时间】:2011-03-22 07:52:30
【问题描述】:

PHP:: 简单的html dom parser(utf-8、windows-255等)如何获取网页的charset值?

备注:必须使用html dom parser http://simplehtmldom.sourceforge.net

Example1 网页字符集输入:

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">

结果:utf-8



Example2 网页字符集输入:

<meta content="text/html; charset=windows-255" http-equiv="Content-Type">

结果:windows-255

编辑:

我试试这个(但它不起作用):

$html = file_get_html('http://www.google.com/');
$el=$html->find('meta[content]',0);
echo $el->charset; 

应该改变什么? (我知道 $el->charset 不起作用)

谢谢

【问题讨论】:

  • //meta[@http-equiv="Content-Type"]/@content 运行 xpath 查询。您必须自己解析属性值。
  • @Frank SimpleHTMLDom 不能做 Xpath
  • 实际使用 DOM 而不是字符串解析的建议第三方替代方案:phpQueryZend_DomFluentDom

标签: php parsing html-parsing simple-html-dom php-parser


【解决方案1】:

你必须使用正则表达式匹配字符串(我希望你有 PCRE...)。

$el=$html->find('meta[http-equiv=Content-Type]',0)
$fullvalue = $el->content;
preg_match('/charset=(.+)/', $fullvalue, $matches);
echo $matches[1];

不是很健壮,但应该可以工作。

【讨论】:

  • 谢谢!我修复了一点,它的作品看到我的答案修复。 $html = file_get_html('google.com/'); $el=$html->find('元[内容]',0); $fullvalue = $el->内容; preg_match('/charset=(.+)/', $fullvalue, $matches); echo substr($matches[0], strlen("charset="));
  • 别那样做,我搞错了。应该是$matches[1]。这使它更快、更可靠。
【解决方案2】:

感谢 MvanGeest 的回答 - 我只是修复了一点,它的工作很完美。

$html = file_get_html('http://www.google.com/');
$el=$html->find('meta[content]',0);
$fullvalue = $el->content;
preg_match('/charset=(.+)/', $fullvalue, $matches);
echo substr($matches[0], strlen("charset="));

【讨论】:

  • 奇怪...它对我有用。不过,您不需要substr……只需$matches[1]。我使用 Google 对其进行了测试。
【解决方案3】:
$dd = new DOMDocument;
$dd->loadHTML($data);
foreach ($dd->getElementsByTagName("meta") as $m) {
    if (strtolower($m->getAttribute("http-equiv")) == "content-type") {
        $v = $m->getAttribute("content");
        if (preg_match("#.+?/.+?;\\s?charset\\s?=\\s?(.+)#i", $v, $m))
            echo $m[1];
    }
}

请注意,DOM 扩展会将所有数据隐式转换为 UTF-8。

【讨论】:

  • 现在这比我写的要强大一点... :)
  • 感谢您提供此选项,因为拥有 utf-8 数据非常重要。
  • @Mva 是的,Content-Type 有时写成“Content-type”。至少在 http 标头中,大小写无关紧要。
  • DomDocument 不总是将正确的文本转换为 utf-8。我仍在努力解决这个问题。
猜你喜欢
  • 2017-09-09
  • 2013-03-23
  • 1970-01-01
  • 2016-01-08
  • 2016-02-22
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多