【问题标题】:Convert a UTF-8 string to/from 7-bit XML in PHP在 PHP 中将 UTF-8 字符串转换为/从 7 位 XML
【发布时间】:2010-09-12 05:02:43
【问题描述】:

如何将 UTF-8 字符串(即 8 位字符串)转换为/从 XML 兼容的 7 位字符串(即带有数字实体的可打印 ASCII)?

encode() 函数这样:

encode("“£”") -> "“£”"

decode() 也很有用:

decode("“£”") -> "“£”"

PHP 的 htmlenties()/html_entity_decode() 对没有做正确的事情:

htmlentities(html_entity_decode("“£”")) ->
  "“£”"

费力地指定类型会有所帮助,但仍会返回与 XML 不兼容的命名实体,而不是数字实体:

htmlentities(html_entity_decode("“£”", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") ->
  "“£”"

【问题讨论】:

    标签: php html xml unicode utf-8


    【解决方案1】:

    这是一种解决方法,但我读过一些关于 iconv() 的内容,我认为它不会为您提供数字实体(未经过测试)

    function decode( $string )
    {
      $doc = new DOMDocument( "1.0", "UTF-8" ); 
      $doc->LoadXML( '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<x />', LIBXML_NOENT );
      $doc->documentElement->appendChild( $doc->createTextNode( $string ) );
      $output = $doc->saveXML( $doc );
      $output = preg_replace( '/<\?([^>]+)\?>/', '', $output ); 
      $output = str_replace( array( '<x>', '</x>' ), array( '', '' ), $output );
      return trim( $output );
    }
    

    不过,我已经对此进行了测试。稍后我可能会反过来,只是不要屏住呼吸;-)

    【讨论】:

      【解决方案2】:

      mb_encode_numericentity 正是这样做的。

      【讨论】:

      • 太棒了,我还不知道那个:)
      • 我认为 mb_encode_numericentity 会做正确的事情,但找出正确的论点是困难的。 (困难的部分似乎是保留(即不转换)可打印的 ASCII 和标点字符。(例如,“&”需要转到“&”,但“^”可以保持原样。)
      猜你喜欢
      • 1970-01-01
      • 2011-05-15
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2016-07-13
      • 2013-03-02
      • 1970-01-01
      相关资源
      最近更新 更多