以下汇集整理PHP解析XML方法。
books.xml文件 -
-
-
- Harry Potter
- J K. Rowling
-
-
- Everyday Italian
- Giada De Laurentiis
-
复制代码
DOMDocument方法解析 - $doc=new DOMDocument(); //创建DOMDocument对象
- $doc->load("books.xml"); //加载XML文件
- $bookDom=$doc->getElementsByTagName("book"); //获取所有的book标签
- foreach($bookDom as $book){ //解析xml
- $title = $book->getElementsByTagName("title")->item(0)->nodeValue;
- $author = $book->getElementsByTagName("author")->item(0)->nodeValue;
- echo "title:".$title."
";
- echo "author:".$author."
";
- echo "****************************
";
- }
- ?>
复制代码
xml-parser方法解析 - $file = "books.xml";
- $data = file_get_contents($file); //读取xml文件
- $parser = xml_parser_create(); //创建解析器
- xml_parse_into_struct($parser, $data, $vals, $index); //将XML数据解析到数组中
- 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']) ? $value['attributes'] : "";
- $val = isset($value['value']) ? $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 "
";
- print_r($arr);
- echo "
";
- ?>
复制代码
simplexml方法解析 - $file="books.xml";
- $xml = simplexml_load_file($file); //载入books.xml
- echo "
";
- print_r($xml);
- echo "
";
- ?>
复制代码 |