在网页开发中,获取并解析 xml 数据是非常常见的操作。本文将重点介绍如何使用 php 爬虫获取并解析 xml 数据。
一、获取 XML 数据
cURL 库是一个非常常用的获取数据的 PHP 库。可以使用以下代码从某个网站上获取 XML 数据:
$url = 'http://example.com/example.xml'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $xml = curl_exec($ch); curl_close($ch);
这里我们使用了 curl_init() 初始化一个 cURL 对象,并且设置了 CURLOPT_URL 参数为目标 URL。将 CURLOPT_RETURNTRANSFER 参数设置为 1,将会使 cURL 返回一个字符串而不是直接输出内容。
在 cURL 库取得 XML 数据的同时, file_get_contents() 方式也可以取得 XML 数据。我们可以按照下面的例子来达到此目的:
立即学习“PHP免费学习笔记(深入)”;
$url = 'http://example.com/example.xml'; $xml = file_get_contents($url);
二、解析 XML 数据
PHP 提供了多种方法来解析 XML 数据。
SimpleXML 是 PHP 中一个非常易于使用的 XML 解析器。我们可以按照下面的代码来使用 SimpleXML:
$xml = simplexml_load_string($xml);
这里我们使用了 simplexml_load_string() 方法来解析 XML 字符串并将其转换为对象。
例如,假设我们有以下 XML 文档:
<?xml version="1.0" encoding="UTF-8" ?>
<bookstore>
<book>
<title>PHP 7 Programming Blueprints</title>
<author>Vikram Vaswani</author>
<price>28.99</price>
</book>
<book>
<title>Mastering PHP 7</title>
<author>Chad Russell</author>
<price>39.99</price>
</book>
</bookstore>我们可以使用以下代码来访问和输出此 XML 数据:
foreach ($xml->book as $book) {
echo "Title: " . $book->title . "<br>";
echo "Author: " . $book->author . "<br>";
echo "Price: " . $book->price . "<br>";
}输出结果如下:
Title: PHP 7 Programming Blueprints Author: Vikram Vaswani Price: 28.99 Title: Mastering PHP 7 Author: Chad Russell Price: 39.99
DOMDocument 是另一个 PHP 中常用的 XML 解析器。我们可以按照下面的代码来使用 DOMDocument:
$doc = new DOMDocument();
$doc->loadXML($xml);
$books = $doc->getElementsByTagName("book");
foreach ($books as $book) {
$titles = $book->getElementsByTagName("title");
$title = $titles->item(0)->nodeValue;
$authors = $book->getElementsByTagName("author");
$author = $authors->item(0)->nodeValue;
$prices = $book->getElementsByTagName("price");
$price = $prices->item(0)->nodeValue;
echo "Title: " . $title . "<br>";
echo "Author: " . $author . "<br>";
echo "Price: " . $price . "<br>";
}这里我们使用了 DOMDocument 类来解析 XML 文档,然后利用 getElementsByTagName() 方法获取特定的元素。最后输出结果与 SimpleXML 解析器相同。
三、总结
在本篇文章中,我们学习了如何使用 PHP 爬虫获取并解析 XML 数据,其中包括使用 cURL 库和 file_get_contents() 函数获取 XML 数据,使用 SimpleXML 和 DOMDocument 解析 XML 数据。希望本文对您有所帮助。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号