溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

PHP解析XML有哪些方法

發布時間:2020-07-20 09:18:54 來源:億速云 閱讀:213 作者:Leah 欄目:編程語言

這篇文章運用簡單易懂的例子給大家介紹PHP解析XML有哪些方法,代碼非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

不管是桌面軟件開發,還是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;
?>

關于PHP解析XML有哪些方法就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女