【使用DomDocument解析】
- <?PHP
- header("Content-type:text/html; Charset=utf-8");
- $url = "http://www.google.com/hhh/api?weather=shenzhen";
- // 加载XML内容
- $content = file_get_contents($url);
- $content = get_utf8_string($content);
- $dom = DOMDocument::loadXML($content);
- /*此处也可使用如下所示的代码,
- $dom = new DOMDocument();
- $dom->load($url);
- */
- $elements = $dom->getElementsByTagName("current_conditions");
- $element = $elements->item(0);
- $condition = get_google_xml_data($element, "condition");
- $temp_c = get_google_xml_data($element, "temp_c");
- echo '天气:', $condition, '<br />';
- echo '温度:', $temp_c, '<br />';
- function get_utf8_string($content) {
- // 将一些字符转化成utf8格式
- $encoding = mb_detect_encoding($content, array('ASCII','UTF-8','GB2312','GBK','BIG5'));
- return mb_convert_encoding($content, 'utf-8', $encoding);
- }
- function get_google_xml_data($element, $tagname) {
- $tags = $element->getElementsByTagName($tagname);
- // 取得所有的
- $tagname$tag = $tags->item(0);
- // 获取第一个以$tagname命名的标签
- if ($tag->hasAttributes()) {
- // 获取data属性
- $attribute = $tag->getAttribute("data");
- return $attribute;
- }else {
- return false;
- }
- }
复制代码
这只是一个简单的示例. 仅包括了loadXML, item, getAttribute,getElementsByTagName等方法,还有一些有用的方法。 【XMLReader】 当我们要用php解读xml的内容时,有很多物件提供函式,让我们不用一个一个字元去解析,而只要根据标签和属性名称,就能取出文件中的属性与内容了,相较之下方便许多。其中XMLReader循序地浏览过xml档案的节点,可以想像成游标走过整份文件的节点,并抓取需要的内容
- <?php
- header("Content-type:text/html; Charset=utf-8");
- $url = "http://www.google.com/hhh/api?weather=shenzhen";
- // 加载XML内容
- $xml = new XMLReader();
- $xml->open($url);
- $condition = '';
- $temp_c = '';
- while ($xml->read()) {
- // echo $xml->name, "==>", $xml->depth, "<br>";
- if (!empty($condition) && !empty($temp_c)) {
- break;
- }
- if ($xml->name == 'condition' && empty($condition)) {
- // 取第一个condition
- $condition = $xml->getAttribute('data');
- }
- if ($xml->name == 'temp_c' && empty($temp_c)) {
- // 取第一个temp_c
- $temp_c = $xml->getAttribute('data');
- }
- $xml->read();
- }
- $xml->close();
- echo '天气:', $condition, '<br />';
- echo '温度:', $temp_c, '<br />';
复制代码
我们只是需要取第一个condition和第一个temp_c,于是遍历所有的节点,将遇到的第一个condition和第一个temp_c写入变量,最后输出。【DOMXPath】
- <?php
- header("Content-type:text/html; Charset=utf-8");
- $url = "http://www.google.com/hhh/api?weather=shenzhen";
- // 加载XML内容
- $dom = new DOMDocument();
- $dom->load($url);
- $xpath = new DOMXPath($dom);
- $element = $xpath->query("/xml_api_reply/weather/current_conditions")->item(0);
- $condition = get_google_xml_data($element, "condition");
- $temp_c = get_google_xml_data($element, "temp_c");
- echo '天气:', $condition, '<br />';
- echo '温度:', $temp_c, '<br />';
- function get_google_xml_data($element, $tagname) {
- $tags = $element->getElementsByTagName($tagname);
- // 取得所有的$tagname
- $tag = $tags->item(0);
- // 获取第一个以$tagname命名的标签
- if ($tag->hasAttributes()) {
- // 获取data属性
- $attribute = $tag->getAttribute("data");
- return $attribute;
- }else {
- return false;
- }
- }
复制代码
|