+ -
当前位置:首页 → 问答吧 → 新手求教xml转数组的问题

新手求教xml转数组的问题

时间:2011-09-29

来源:互联网

<?xml version="1.0"?>
<XMLData>
<Ver>3.1</Ver>
<ItemList>
<Item>
<ItemID>50000</ItemID>
<Name>football</Name>
<Price>20</Price>
</Item>
<Item>
<ItemID>53566</ItemID>
<Name>basketball</Name>
<Price>40</Price>
</Item>
....
</ItemList>
</XMLData>



如上的xml,怎样才能输出类似array[$ItemID]=array('Name' => $Name,
                                                                      'price'=>$price);
即是array[53566]=array('name' => basketball,
                                   'price' => 40);


新手,求不吝指教

作者: lewis501   发布时间: 2011-09-29

  1. $items=array();
  2. $hd=fopen("test.xml",'r');
  3. $content=fread($hd,filesize("test.xml"));
  4. fclose($hd);
  5. preg_match_all('|<Item>(.+?)<\/Item>|s',$content,$matches);

  6. for($i=0;$i<count($matches[1]);$i++){
  7.         preg_match_all('|<ItemID>(.+?)<\/ItemID>|s',$matches[1][$i],$ItemID);
  8.         preg_match_all('|<Name>(.+?)<\/Name>|s',$matches[1][$i],$Name);
  9.         preg_match_all('|<Price>(.+?)<\/Price>|s',$matches[1][$i],$Price);
  10.         $items[$ItemID[1][0]]=array("name"=>$Name[1][0],"price"=>$Price[1][0]);
  11. }
  12. var_dump($items);
复制代码
test.xml如下
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <XMLData>
  3. <Ver>3.1</Ver>
  4.         <ItemList>
  5.                 <Item>
  6.                         <ItemID>50000</ItemID>
  7.                         <Name>football</Name>
  8.                         <Price>20</Price>
  9.                 </Item>
  10.                 <Item>
  11.                         <ItemID>53566</ItemID>
  12.                         <Name>basketball</Name>
  13.                         <Price>40</Price>
  14.                 </Item>
  15.         </ItemList>
  16. </XMLData>
复制代码

作者: targer   发布时间: 2011-09-29

请学习手册
http://www.php.net/manual/en/function.xml-parse.php

作者: iminto   发布时间: 2011-09-29

相关阅读 更多