SimpleXML作为PHP核心的组成部分,可以把XML转换为对象,但是有时候,我需要对输出的xml格式设置编码;
代码:
1 2 | $XML = new SimpleXMLElement( "<foo />" ); echo ( $XML ->asXML()); |
输出结果:
1 2 | <? xml version = "1.0" ?> < foo /> |
如果想输出:
1 2 | <? xml version = "1.0" encoding = "UTF-8" ?> < foo /> |
可以使用以下几个方法,实现XML格式编码:
方法一、用addAttribute()函数给 SimpleXML 元素添加一个属性
1 | $xml ->addAttribute( 'encoding' , 'UTF-8' ); |
方法二、使用简单的替换
1 | $outputXML = str_replace ( '<?xml version="1.0"?>' , '<?xml version="1.0" encoding="UTF-8"?>' , $outputXML ); |
方法三、使用正规则替换
1 | $outputXML =preg_replace( '/<\?\s*xml([^\s]*)\?>/' '<?xml $1 encoding="UTF-8"?>' , $outputXML ); |
方法四、设置DomDocument对象编码
1 2 3 | $xml =dom_import_simplexml( $simpleXML ); $xml ->xmlEndoding= 'UTF-8' ; $outputXML = $xml ->saveXML(); |
参考资料:
http://www.w3school.com.cn/php/php_ref_simplexml.asp
原创文章,转载请注明:转载自Web开发笔记 | php输出xml格式编码
本文链接地址:https://www.magentonotes.com/php-output-xml-encode.html
Comments on this entry are closed.