PHP解析XML可以利用simplexml_load_string()或simplexml_load_file()來解析

$string = <<<XML
		<books>
			<book>
				<author>Jack Herrington</author>
				<title version="1">PHP Hacks</title>
				<publisher>O'Reilly</publisher>
			</book>
			<book>
				<author>Jack Herrington</author>
				<title version="2">Podcasting Hacks</title>
				<publisher>O'Reilly</publisher>
			</book>
		</books>
XML;

$xml = simplexml_load_string( $string ); //解析XML字串,simplexml_load_file用來解析xml檔案
foreach( $xml -> book as $book) //用foreach讀取各個book標籤
{
	echo "author: ".$book -> author."<br/>"; // author內容
	echo "title: ".$book -> title."<br/>"; // title內容
	echo "title version屬性: ".$book -> title -> attributes() -> version."<br/>"; // title的version屬性 
	echo "publisher: ".$book -> publisher."<br/>"; // publisher內容
}

XmlToArray

$xml = simplexml_load_string( $string );
$json = json_encode($xml);
$arr = json_decode($json, true);
Categories: PHP