溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP解析XML有哪些方法

發(fā)布時(shí)間:2020-07-20 09:18:54 來(lái)源:億速云 閱讀:158 作者:Leah 欄目:編程語(yǔ)言

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

不管是桌面軟件開(kāi)發(fā),還是WEB應(yīng)用,XML無(wú)處不在!

然而在平時(shí)的工作中,僅僅是使用一些已經(jīng)封裝好的類對(duì)XML對(duì)于處理,包括生成,解析等。假期有空,于是將PHP中的幾種XML解析方法總結(jié)如下:

以解析Google API 接口提供的天氣情況為例,我們?nèi)〗裉斓奶鞖饧皻鉁亍?/p>

API地址:http://www.google.com/ig/api?weather=shenzhen

【XML文件內(nèi)容】

<?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內(nèi)容
$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) {    //  將一些字符轉(zhuǎn)化成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);  //  獲取第一個(gè)以$tagname命名的標(biāo)簽
    if ($tag->hasAttributes()) {    //  獲取data屬性
        $attribute = $tag->getAttribute("data");
        return $attribute;
    }else {
        return false;
    }
}
?>

這只是一個(gè)簡(jiǎn)單的示例,僅包括了loadXML, item, getAttribute,getElementsByTagName等方法,還有一些有用的方法,這個(gè)依據(jù)你的實(shí)際需要。

【XMLReader】

當(dāng)我們要用php解讀xml的內(nèi)容時(shí),有很多物件提供函式,讓我們不用一個(gè)一個(gè)字元去解析,而只要根據(jù)標(biāo)簽和屬性名稱,就能取出文件中的屬性與內(nèi)容了,相較之下方便許多。其中XMLReader循序地瀏覽過(guò)xml檔案的節(jié)點(diǎn),可以想像成游標(biāo)走過(guò)整份文件的節(jié)點(diǎn),并抓取需要的內(nèi)容。

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/api?weather=shenzhen";
 
//  加載XML內(nèi)容
$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)) {  //  取第一個(gè)condition
            $condition = $xml->getAttribute('data');
      }
 
      if ($xml->name == 'temp_c' && empty($temp_c)) {    //  取第一個(gè)temp_c
          $temp_c = $xml->getAttribute('data');
      }
 
      $xml->read();
}
 
$xml->close();
echo '天氣:', $condition, '<br />';
echo '溫度:', $temp_c, '<br />';

我們只是需要取第一個(gè)condition和第一個(gè)temp_c,于是遍歷所有的節(jié)點(diǎn),將遇到的第一個(gè)condition和第一個(gè)temp_c寫入變量,最后輸出。

【DOMXPath】

這種方法需要使用DOMDocument對(duì)象創(chuàng)建整個(gè)文檔的結(jié)構(gòu),

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/api?weather=shenzhen";
 
//  加載XML內(nèi)容
$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);  //  獲取第一個(gè)以$tagname命名的標(biāo)簽
    if ($tag->hasAttributes()) {    //  獲取data屬性
        $attribute = $tag->getAttribute("data");
        return $attribute;
    }else {
        return false;
    }
}
?>

【xml_parse_into_struct】

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

該函數(shù)將 XML 文件解析到兩個(gè)對(duì)應(yīng)的數(shù)組中,index 參數(shù)含有指向 values 數(shù)組中對(duì)應(yīng)值的指針。最后兩個(gè)數(shù)組參數(shù)可由指針傳遞給函數(shù)。

注意: xml_parse_into_struct() 失敗返回 0,成功返回 1。這和 FALSE 與 TRUE 不同,使用例如 === 的運(yùn)算符時(shí)要注意。

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/api?weather=shenzhen";
 
//  加載XML內(nèi)容
$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中可用

這個(gè)在google的官方文檔中有相關(guān)的例子,如下:

// Charset: utf-8
/**
  * 用php Simplexml 調(diào)用google天氣預(yù)報(bào)api,和g官方的例子不一樣
  * google 官方php domxml 獲取google天氣預(yù)報(bào)的例子
  * 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.= "當(dāng)前: {$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;
?>

關(guān)于PHP解析XML有哪些方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI