当前位置:首页 > PHP文摘 > 列表

PHP如何将XML转成数组

发布:smiling 来源: PHP粉丝网  添加日期:2019-10-10 18:36:23 浏览: 评论:0 

如果你使用 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.  
  3. $string = <<<xml <?xml="" version="1.0" ?="">  
  4.  
  5. <document> 
  6.  
  7.  <title>Forty What?</title> 
  8.  
  9.  <from>Joe</from> 
  10.  
  11.  <to>Jane</to> 
  12.  
  13.  I know that's the answer -- but what's the question?  
  14.  
  15. </document> 
  16.  
  17. XML; 
  18.  
  19. $xml=simplexml_load_string($string); 
  20.  
  21. $data = json_decode(json_encode($xml),TRUE); 
  22.  
  23. var_dump( $xml ); 
  24.  
  25. var_dump( $data ); 
  26.  
  27. </xml> 
  1. object(SimpleXMLElement)[1] 
  2.  
  3.  public 'title' => string 'Forty What?' (length=11) 
  4.  
  5.  public 'from' => string 'Joe' (length=3) 
  6.  
  7.  public 'to' => string 'Jane' (length=4) 
  8.  
  9.  public 'body' => string ' 
  10.  
  11.  I know that's the answer -- but what's the question? 
  12.  
  13.  ' (length=57) 
  14.  
  15. array 
  16.  
  17.  'title' => string 'Forty What?' (length=11) 
  18.  
  19.  'from' => string 'Joe' (length=3) 
  20.  
  21.  'to' => string 'Jane' (length=4) 
  22.  
  23.  'body' => string ' 
  24.  
  25.  I know that's the answer -- but what's the question? 
  26.  
  27.  ' (length=57) 

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

Tags: XML转成数组

分享到: