您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“php解析xml方法的實(shí)例講解”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
books.xml文件如下:
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book category="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
<?php //創(chuàng)建一個(gè)DOMDocument對(duì)象 $doc=new DOMDocument(); //加載XML文件 $doc->load("books.xml"); //獲取所有的book標(biāo)簽 $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>"; } ?>
2、xml_parse_into_struct
創(chuàng)建解析器,將xml數(shù)據(jù)解析到數(shù)組,釋放解析器,再有就是從數(shù)組中提取想要的值。
<?php // 讀取xml文件 $file = "books.xml"; $data = file_get_contents($file); // 創(chuàng)建解析器 $parser = xml_parser_create(); // 將 XML 數(shù)據(jù)解析到數(shù)組中 xml_parse_into_struct($parser, $data, $vals, $index); // 釋放解析器 xml_parser_free($parser); // 數(shù)組處理 $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 "<pre>"; print_r($arr); echo "</pre>"; ?>
3、用 SAX 解析器讀取 XML-----XML Simple API(SAX)解析器
<?php $file="books.xml"; $xml = simplexml_load_file($file); echo "<pre>"; print_r($xml); echo "</pre>"; ?>
“php解析xml方法的實(shí)例講解”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。