>  기사  >  백엔드 개발  >  PHP로 XML을 구문 분석하는 여러 가지 방법(코드 포함)

PHP로 XML을 구문 분석하는 여러 가지 방법(코드 포함)

青灯夜游
青灯夜游앞으로
2020-07-16 16:23:063340검색

PHP로 XML을 구문 분석하는 여러 가지 방법(코드 포함)

데스크톱 소프트웨어 개발이든 웹 애플리케이션이든 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 />';

첫 번째 조건과 첫 번째 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(리소스 파서, 문자열 데이터, 배열 및 값 ​​[, array &index] )

이 함수는 XML 파일을 두 개의 해당 배열로 구문 분석합니다. index 매개 변수에는 값 배열의 해당 값에 대한 포인터가 포함되어 있습니다. 마지막 두 개의 배열 매개변수는 포인터를 통해 함수에 전달될 수 있습니다.

참고: 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제