处理内容有&特殊字符thinkphp返回xml无法解析的问题<![CDATA[xxx]]>

处理内容有&特殊字符thinkphp返回xml无法解析的问题<![CDATA[xxx]]>

// xml 转义特殊字符 如&'" <![CDATA["标记开始,以"]]>标记结束
不能直接把data进行for循环,否则里面的数组对象就变成一个对象字符了

// xml 转义特殊字符 如&'" <![CDATA["标记开始,以"]]>标记结束
$xml .= (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : '<![CDATA['.$val.']]>';
必须是最终文本值才能加上这个<![CDATA[xxx]]>
测试xml特殊字符&&&#@R<>>d?#dfasf*()@!~-=+_''"":;,./

ThinkPHP/Common/functions.php

 1 /**
 2  * XML编码
 3  * @param mixed $data 数据
 4  * @param string $root 根节点名
 5  * @param string $item 数字索引的子节点名
 6  * @param string $attr 根节点属性
 7  * @param string $id   数字索引子节点key转换的属性名
 8  * @param string $encoding 数据编码
 9  * @return string
10  */
11 function xml_encode($data, $root='think', $item='item', $attr='', $id='id', $encoding='utf-8') {
12     if(is_array($attr)){
13         $_attr = array();
14         foreach ($attr as $key => $value) {
15             $_attr[] = "{$key}="{$value}"";
16         }
17         $attr = implode(' ', $_attr);
18     }
19     $attr   = trim($attr);
20     $attr   = empty($attr) ? '' : " {$attr}";
21     $xml    = "<?xml version="1.0" encoding="{$encoding}"?>";
22     $xml   .= "<{$root}{$attr}>";
23     $xml   .= data_to_xml($data, $item, $id);
24     $xml   .= "</{$root}>";
25     return $xml;
26 }
27 
28 /**
29  * 数据XML编码
30  * @param mixed  $data 数据
31  * @param string $item 数字索引时的节点名称
32  * @param string $id   数字索引key转换为的属性名
33  * @return string
34  */
35 function data_to_xml($data, $item='item', $id='id') {
36     $xml = $attr = '';
37     foreach ($data as $key => $val) {
38         if(is_numeric($key)){
39             $id && $attr = " {$id}="{$key}"";
40             $key  = $item;
41         }
42         $xml    .=  "<{$key}{$attr}>";
43         // xml 转义特殊字符 如& 以<![CDATA[标记开始,以]]>标记结束,必须是最终文本值才能加上这个<![CDATA[xxx]]>
44         $xml    .=  (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : '<![CDATA['.$val.']]>';
45         $xml    .=  "</{$key}>";
46     }
47     return $xml;
48 }

---------------------------------
&lt; < 小于号
&gt; > 大于号
&amp; & 和
&apos; ' 单引号
&quot; " 双引号
实体必须以符号"&"开头,以符号";"结尾。 注意: 只有"<" 字符和"&"字符对于XML来说是严格禁止使用的。
剩下的都是合法的,为了减少出错,使用实体是一个好习惯。

基本的html转义字符特殊字符
字符 十进制    转义字符
“      &#34;   &quot;
&     &#38;   &amp;
<     &#60;   &lt;
>     &#62;   &gt;
空格  &#160; &nbsp;

-----------------------------

原文地址:https://www.cnblogs.com/zdz8207/p/thinkphp-data_to_xml.html