1. 使用 SimpleXML:
<?php
// XML 数据
$xmlString = '
<bookstore>
<book>
<title>PHP Programming</title>
<author>John Doe</author>
<price>29.95</price>
</book>
<book>
<title>Web Development</title>
<author>Jane Smith</author>
<price>39.99</price>
</book>
</bookstore>
';
// 使用 SimpleXML 解析 XML 数据
$xml = simplexml_load_string($xmlString);
// 访问 XML 数据
foreach ($xml->book as $book) {
echo "Title: " . $book->title . "<br>";
echo "Author: " . $book->author . "<br>";
echo "Price: $" . $book->price . "<br><br>";
}
?>
2. 使用 DOMDocument:
<?php
// XML 数据
$xmlString = '
<bookstore>
<book>
<title>PHP Programming</title>
<author>John Doe</author>
<price>29.95</price>
</book>
<book>
<title>Web Development</title>
<author>Jane Smith</author>
<price>39.99</price>
</book>
</bookstore>
';
// 使用 DOMDocument 解析 XML 数据
$dom = new DOMDocument;
$dom->loadXML($xmlString);
// 获取 XML 元素
$books = $dom->getElementsByTagName('book');
// 遍历并输出数据
foreach ($books as $book) {
$title = $book->getElementsByTagName('title')->item(0)->nodeValue;
$author = $book->getElementsByTagName('author')->item(0)->nodeValue;
$price = $book->getElementsByTagName('price')->item(0)->nodeValue;
echo "Title: $title <br>";
echo "Author: $author <br>";
echo "Price: $$price <br><br>";
}
?>
这两种方法都允许你遍历XML数据,选择所需的元素,并提取其中的信息。选择使用SimpleXML还是DOMDocument通常取决于个人偏好和具体需求。SimpleXML更简单易用,而DOMDocument提供了更多的灵活性和功能。
转载请注明出处:http://www.pingtaimeng.com/article/detail/13867/PHP