当前位置:Gxlcms > PHP教程 > 数组与XML文件相互转换

数组与XML文件相互转换

时间:2021-07-01 10:21:17 帮助过:13人阅读

这次给大家带来数组与XML文件相互转换,数组与XML文件相互转换的注意事项有哪些,下面就是实战案例,一起来看一下。

最近搞微信支付,微信服务器返回的都是XML文件,所以需要转换成数组,才会便于操作,好了话不多说,直接上代码:

1. XML转数组

  1. /**
  2. * 将xml转为array
  3. * @param string $xml xml字符串或者xml文件名
  4. * @param bool $isfile 传入的是否是xml文件名
  5. * @return array 转换得到的数组
  6. */
  7. function xmlToArray($xml,$isfile=false){
  8. //禁止引用外部xml实体
  9. libxml_disable_entity_loader(true);
  10. if($isfile){
  11. if(!file_exists($xml)) return false;
  12. $xmlstr = file_get_contents($xml);
  13. }else{
  14. $xmlstr = $xml;
  15. }
  16. $result= json_decode(json_encode(simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  17. return $result;
  18. }

用法示例:

  1. $xmlDoc=<<<ETO
  2. <books>
  3. <book>
  4. <author>Jack Herrington</author>
  5. <title>PHP Hacks</title>
  6. <publisher>O'Reilly</publisher>
  7. </book>
  8. <book>
  9. <author>Jack Herrington</author>
  10. <title>Podcasting Hacks</title>
  11. <publisher>O'Reilly</publisher>
  12. </book>
  13. <book>
  14. <author>XML格式化</author>
  15. <title>脚本之家在线工具</title>
  16. <publisher>tools.jb51.net</publisher>
  17. </book>
  18. </books>
  19. ETO;
  20. $relarr=xmlToArray($xmlDoc);
  21. print_r($relarr);

运行结果:

  1. Array
  2. (
  3. [book] => Array
  4. (
  5. [0] => Array
  6. (
  7. [author] => Jack Herrington
  8. [title] => PHP Hacks
  9. [publisher] => O'Reilly
  10. )
  11. [1] => Array
  12. (
  13. [author] => Jack Herrington
  14. [title] => Podcasting Hacks
  15. [publisher] => O'Reilly
  16. )
  17. [2] => Array
  18. (
  19. [author] => XML格式化
  20. [title] => 脚本之家在线工具
  21. [publisher] => tools.jb51.net
  22. )
  23. )
  24. )

2. 数组转XML

  1. /**
  2. * 数组转xml字符
  3. * @param string $xml xml字符串
  4. **/
  5. function arrayToXml($data){
  6. if(!is_array($data) || count($data) <= 0){
  7. return false;
  8. }
  9. $xml = "<xml>";
  10. foreach ($data as $key=>$val){
  11. if (is_numeric($val)){
  12. $xml.="<".$key.">".$val."</".$key.">";
  13. }else{
  14. $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
  15. }
  16. }
  17. $xml.="</xml>";
  18. return $xml;
  19. }

用法示例:

  1. $arrDoc= array("author"=>"XML格式化","title"=>"脚本之家在线工具","publisher"=>"tools.jb51.net");
  2. $xmlrel=arrayToXml($arrDoc);
  3. //运行结果:<xml><author><![CDATA[XML格式化]]></author><title><![CDATA[脚本之家在线工具]]></title><publisher><![CDATA[tools.jb51.net]]></publisher></xml>

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

Vue制作图片轮播

JS获取select下拉框中第一顺位元素内的值

安装Electron失败怎么处理

以上就是数组与XML文件相互转换的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行