使用了Document Object Model (DOM) extension。
XML范例文件:test.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <mynotes> <note> <tasks>Validate data</tasks> <details>Validate data in SQL2005 Database with SQL manager</details> </note> <note> <tasks>Download Music</tasks> <details>Download latest music from site abc</details> </note> </mynotes>
PHP代码:
<? // DOMElement->getElementsByTagName() -- Gets elements by tagname // nodeValue : The value of this node, depending on its type. // Load XML File. You can use loadXML if you wish to load XML data from a string $objDOM = new DOMDocument(); $objDOM->load("test.xml"); //make sure path is correct $note = $objDOM->getElementsByTagName("note"); // for each note tag, parse the document and get values for // tasks and details tag. foreach( $note as $value ) { $tasks = $value->getElementsByTagName("tasks"); $task = $tasks->item(0)->nodeValue; $details = $value->getElementsByTagName("details"); $detail = $details->item(0)->nodeValue; echo "$task :: $detail <br>"; } ?>
处理过程中碰到一个错误:“DOMDocument::LoadXML Extra content at the end of the document in Entity...”
原因是源文件不是标准的XML,没有root element,导致无法生成DOM tree。自己手动加上了一对tag,名字无所谓,因为没有严格的schema校验。
官方参考:http://us3.php.net/manual/en/refs.xml.php
参考:http://www.geekpedia.com/tutorial156_How-to-read-XML-using-PHP-DOM.html
http://www.dave78.com/2008/02/19/domdocumentloadxml-extra-content-at-the-end-of-the-document-in-entity/