A-A+

PHP如何将XML转成数组

2019年10月28日 我爱编程 暂无评论

如果你使用 curl 获取的 xml data

xml=simplexmlloadstring(data);

data[′tk′]=jsondecode(jsonencode(xml),TRUE);

如果是直接获取 URL 数据的话

xml=simplexmlloadfile(data);

data[′tk′]=jsondecode(jsonencode(xml),TRUE);

先把 simplexml 对象转换成 json,再将 json 转换成数组。

代码:

  1. <?php
  2. $string = <<<xml <?xml="" version="1.0" ?="">
  3. <document>
  4.  <title>Forty What?</title>
  5.  <from>Joe</from>
  6.  <to>Jane</to>
  7.  I know that's the answer -- but what's the question?
  8. </document>
  9. XML;
  10. $xml=simplexml_load_string($string);
  11. $data = json_decode(json_encode($xml),TRUE);
  12. var_dump( $xml );
  13. var_dump( $data );
  14. </xml>
  1. object(SimpleXMLElement)[1]
  2.  public 'title' => string 'Forty What?' (length=11)
  3.  public 'from' => string 'Joe' (length=3)
  4.  public 'to' => string 'Jane' (length=4)
  5.  public 'body' => string '
  6.  I know that's the answer -- but what's the question?
  7.  ' (length=57)
  8. array
  9.  'title' => string 'Forty What?' (length=11)
  10.  'from' => string 'Joe' (length=3)
  11.  'to' => string 'Jane' (length=4)
  12.  'body' => string '
  13.  I know that's the answer -- but what's the question?
  14.  ' (length=57)

以上就是本文的全部内容,希望对大家的学习有所帮助。

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录