相思资源网 Design By www.200059.com

本文以实例形式详细讲述了php解析xml方法。分享给大家供大家参考。具体分析如下:

books.xml文件如下:

<"1.0" encoding="ISO-8859-1""children">
 <title lang="en">Harry Potter</title>
 <author>J K. Rowling</author>
 <year>2005</year>
 <price>29.99</price>
 </book>
 <book category="cooking">
 <title lang="en">Everyday Italian</title>
 <author>Giada De Laurentiis</author>
 <year>2005</year>
 <price>30.00</price>
 </book>
 <book category="web" cover="paperback">
 <title lang="en">Learning XML</title>
 <author>Erik T. Ray</author>
 <year>2003</year>
 <price>39.95</price>
 </book>
</bookstore>

1、DOM解析XML

<"books.xml");
 //获取所有的book标签
 $bookDom=$doc->getElementsByTagName("book");
 foreach($bookDom as $book){
  $title = $book->getElementsByTagName("title")->item(0)->nodeValue;
  $author = $book->getElementsByTagName("author")->item(0)->nodeValue;
  $year = $book->getElementsByTagName("year")->item(0)->nodeValue;
  $price = $book->getElementsByTagName("price")->item(0)->nodeValue;
  echo "title:".$title."<br>";
  echo "author:".$author."<br>";
  echo "year:".$year."<br>";
  echo "price:".$price ."<br>";
  echo "***********************************<br>";
 }
"htmlcode">
<"books.xml";
 $data = file_get_contents($file);
 // 创建解析器
 $parser = xml_parser_create();
 // 将 XML 数据解析到数组中
 xml_parse_into_struct($parser, $data, $vals, $index);
 // 释放解析器
 xml_parser_free($parser);
 // 数组处理
 $arr = array();
 $t=0;
 foreach($vals as $value) {
 $type = $value['type'];
 $tag = $value['tag'];
 $level = $value['level'];
 $attributes = isset($value['attributes'])"";
 $val = isset($value['value'])"";
 switch ($type) {
  case 'open':
  if ($attributes != "" || $val != "") {
   $arr[$t]['tag'] = $tag;
   $arr[$t]['attributes'] = $attributes;
   $arr[$t]['level'] = $level;
   $t++;
  } 
  break;
  case "complete":
  if ($attributes != "" || $val != "") {
   $arr[$t]['tag'] = $tag;
   $arr[$t]['attributes'] = $attributes;
   $arr[$t]['val'] = $val;
   $arr[$t]['level'] = $level;
   $t++;
  } 
  break;
 } 
 } 
 echo "<pre>";
 print_r($arr);
 echo "</pre>";
"htmlcode">
<"books.xml";
 $xml = simplexml_load_file($file);
 echo "<pre>";
 print_r($xml);
 echo "</pre>";
?>

希望本文所述对大家的php程序设计有所帮助。

标签:
php,解析xml

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“php解析xml方法实例详解”

暂无php解析xml方法实例详解的评论...