PHP中的XML解析的5種方法


【前言】
   不管是桌面軟件開發,還是WEB應用,XML無處不在!
   然而在平時的工作中,僅僅是使用一些已經封裝好的類對XML對於處理,包括生成,解析等。假期有空,於是將PHP中的幾種XML解析方法總結如下:

   以解析Google API 接口提供的天氣情況為例,我們取今天的天氣及氣溫。
   API地址:http://www.google.com/ig/api?weather=shenzhen

【XML文件內容】

<?xml version="1.0"?>  
<xml_api_reply version="1">  
    <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >  
        <forecast_information>  
            <city data="Shenzhen, Guangdong"/>  
            <postal_code data="shenzhen"/>  
            <latitude_e6 data=""/>  
            <longitude_e6 data=""/>  
            <forecast_date data="2009-10-05"/>  
            <current_date_time data="2009-10-04 05:02:00 +0000"/>  
            <unit_system data="US"/>  
        </forecast_information>  
        <current_conditions>  
            <condition data="Sunny"/>  
            <temp_f data="88"/>  
            <temp_c data="31"/>  
            <humidity data="Humidity: 49%"/>  
            <icon data="/ig/images/weather/sunny.gif"/>  
            <wind_condition data="Wind:  mph"/>  
        </current_conditions>  
    </weather>  
</xml_api_reply>  

【使用DomDocument解析】

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/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/ig/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】
   這種方法需要使用DOMDocument對象創建整個文檔的結構,

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/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;
    }
}
?>

【xml_parse_into_struct】
   說明:int xml_parse_into_struct ( resource parser, string data, array &values [, array &index] )

   該函數將 XML 文件解析到兩個對應的數組中,index 參數含有指向 values 數組中對應值的指針。最后兩個數組參數可由指針傳遞給函數。
   注意: xml_parse_into_struct() 失敗返回 0,成功返回 1。這和 FALSE 與 TRUE 不同,使用例如 === 的運算符時要注意。

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/api?weather=shenzhen";
 
//  加載XML內容
$content = file_get_contents($url);
$p = xml_parser_create();
xml_parse_into_struct($p, $content, $vals, $index);
xml_parser_free($p);
 
echo '天氣:', $vals[$index['CONDITION'][0]]['attributes']['DATA'], '<br />';
echo '溫度:', $vals[$index['TEMP_C'][0]]['attributes']['DATA'], '<br />';

【Simplexml】
   此方法在PHP5中可用
   這個在google的官方文檔中有相關的例子,如下:

// Charset: utf-8
/**
  * 用php Simplexml 調用google天氣預報api,和g官方的例子不一樣
  * google 官方php domxml 獲取google天氣預報的例子
  * http://www.google.com/tools/toolbar/buttons/intl/zh-CN/apis/howto_guide.html
  *
  * @copyright Copyright (c) 2008 <cmpan(at)qq.com>
  * @license New BSD License
  * @version 2008-11-9
  */
 
// 城市,用城市拼音
$city = empty($_GET['city']) ? 'shenzhen' : $_GET['city'];
$content = file_get_contents("http://www.google.com/ig/api?weather=$city&hl=zh-cn");
$content || die("No such city's data");
$content = mb_convert_encoding($content, 'UTF-8', 'GBK');
$xml = simplexml_load_string($content);
 
$date = $xml->weather->forecast_information->forecast_date->attributes();
$html = $date. "<br>\r\n";
 
$current = $xml->weather->current_conditions;
 
$condition = $current->condition->attributes();
$temp_c = $current->temp_c->attributes();
$humidity = $current->humidity->attributes();
$icon = $current->icon->attributes();
$wind = $current->wind_condition->attributes();
 
$condition && $condition = $xml->weather->forecast_conditions->condition->attributes();
$icon && $icon = $xml->weather->forecast_conditions->icon->attributes();
 
$html.= "當前: {$condition}, {$temp_c}°C,<img src='http://www.google.com/ig{$icon}'/> {$humidity} {$wind} <br />\r\n";
 
foreach($xml->weather->forecast_conditions as $forecast) {
    $low = $forecast->low->attributes();
    $high = $forecast->high->attributes();
    $icon = $forecast->icon->attributes();
    $condition = $forecast->condition->attributes();
    $day_of_week = $forecast->day_of_week->attributes();
    $html.= "{$day_of_week} : {$high} / {$low} °C, {$condition} <img src='http://www.google.com/ig{$icon}' /><br />\r\n";
}
 
header('Content-type: text/html; Charset: utf-8');
print $html;
?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM