【问题标题】:Convert parsed text, with php, to utf-8使用 php 将解析的文本转换为 utf-8
【发布时间】:2013-01-15 11:08:12
【问题描述】:

除了我之前关于parsing images and text from complex xml 的问题之外,现在唯一的问题是我没有得到正确的编码。文本为希腊语,xml 文件具有utf-8 编码。 这是解析xml的代码:

$xml = simplexml_load_file('myfile.xml');

$descriptions = $xml->xpath('//item/description');

foreach ( $descriptions as $description_node ) {

    $description_dom = new DOMDocument();
    $description_dom->loadHTML( (string)$description_node );

    $description_sxml = simplexml_import_dom( $description_dom );

    $imgs = $description_sxml->xpath('//img');
    $text = $description_sxml->xpath('//div');

    foreach($imgs as $image){

    echo (string)$image['src'];     
       }

    foreach($text as $t){
    
        echo (string)$t;
       }
    }

如果我echo $description_node,文本看起来不错,但在我得到$description_domsimplexml_import_dom之后,它看起来像这样: Ïε ιÏÎ»Î±Î¼Î¹ÎºÎ­Ï ÎºÎ¿Î¹Î½ÏÏηÏεÏ.使用 mb_convert_encoding 将其变为: ýÃÂñù" ÃÂ。我做错了什么?

【问题讨论】:

  • 您是否尝试添加 from_encoding 参数?像mb_convert_encoding($str, "UTF-7", "EUC-JP"); 也使用正确的编码DomDocument
  • 当您将某些字符串“回显”到浏览器时,请确保您从格式良好的 HTML 页面执行此操作,并指定了 UTF-8 字符集:<!doctype html> <html> <head> <meta charset="utf-8" /> </head> <body> <?php echo $text; ?> </body> </html> 这已经可以让您免于一些无用的头痛。
  • simplexml_load_file 已经在 utf-8 中加载了所有内容,请尝试删除 ,'utf-8' 额外的转换可能
  • @PeterM 是的,但是将它从 ..what 转换为 utf-8?
  • 来自 myfile.xml 的@pano 编码。也许它是不同的编码?如果是这样,请尝试将文件 before 转换为 simplexml_load_file,在这种情况下应使用 simplexml_load_string。也尝试在浏览器中显示原始 xml 文件,看看它是否正确呈现。

标签: php encoding utf-8 xml-parsing


【解决方案1】:

解决方法:在$description_dom = new DOMDocument();之后,我放了这段代码。

$description_html = mb_convert_encoding($description_node, 'HTML-ENTITIES', "UTF-8");

只需将html entities 转换为UTF-8。而不是

$description_dom->loadHTML( (string)$description_node );

现在我加载转换后的 html

$description_dom->loadHTML( (string)$description_html );

【讨论】:

  • 那么,您将特殊字符编码为 html 十六进制值等,对吧?
【解决方案2】:

将此添加到您希望显示文本的 HTML 页面的头部:

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

这应该可以正确渲染字符。

【讨论】:

  • 并确保从 PHP 脚本中删除 $ct=mb_convert_encoding($t, "utf-8")
【解决方案3】:

不要转换任何东西..只需使用正确的声明打印它

header("Content-Type: text/plain; charset=utf-8");

这就是你需要做的。在文件顶部执行此操作。

【讨论】:

  • @pano 从一个非常简单的 php 脚本开始,例如 &lt;?php header("Content-Type: text/plain; charset=utf-8"); echo file_get_contents('myfile.xml'); ?&gt; 。之后,开始逐渐添加您自己的代码,看看它开始失败的地方。
  • 已经做了,在$description_sxml = simplexml_import_dom( $description_dom );之后开始失败
  • @pano 这个功能应该不是问题。目前无权访问文档以进行确认。
  • 如果我 echo $description_node 没关系。如果我echo $description_sxml,不是。
  • @pano 你可以通过$imgs = $description_node-&gt;xpath('//img'); $text = $description_node-&gt;xpath('//div');避免大部分事情
猜你喜欢
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2012-08-04
  • 2018-02-06
  • 2013-01-25
  • 1970-01-01
相关资源
最近更新 更多