ホームページ  >  記事  >  バックエンド開発  >  PHP で XML を解析するためのいくつかの方法 (コード付き)

PHP で XML を解析するためのいくつかの方法 (コード付き)

青灯夜游
青灯夜游転載
2020-07-16 16:23:063340ブラウズ

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 ファイルのノードを順番に参照します。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 />';

最初の条件と最初の temp_c を取得する必要があるだけなので、すべてのノードを走査し、最初に見つかった条件と最初の 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 (リソース パーサー、文字列データ、配列 &values [, 配列 &index])

この関数は、XML ファイルを 2 つの対応する配列に解析します。値へのポイントが含まれます。配列内の対応する値へのポインタ。最後の 2 つの配列パラメーターは、ポインターによって関数に渡すことができます。

注: 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=&#39;http://www.google.com/ig{$icon}&#39;/> {$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=&#39;http://www.google.com/ig{$icon}&#39; /><br />\r\n";
}
 
header('Content-type: text/html; Charset: utf-8');
print $html;
?>

関連する推奨事項: PHP チュートリアル

以上がPHP で XML を解析するためのいくつかの方法 (コード付き)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はcnblogs.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。