5 ways to parse XML in PHP

[Introduction]
   whether it is desktop software development, or WEB applications, XML is everywhere!
   However, in the daily work, the use of only some of which have good package for processing XML classes, including generation, analysis or the like. Free vacation, so the PHP XML parsing of several methods are summarized as follows:

   Weather conditions in order to resolve the Google API interface provides an example, we take today's weather and temperature.
   API Address: http://www.google.com/ig/api?weather=shenzhen

[XML content file]

<?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>  

[A] using DomDocument

? < PHP
 header ( "Content-of the type: text / HTML; Charset = UTF-8" );
 $ url = "http://www.google.com/ig/api?weather=shenzhen" ; 
 
//   load the XML content 
Content $ = file_get_contents ( $ URL );
 $ Content = get_utf8_string ( $ Content );
 $ DOM = the loadXML the DOMDocument :: ( $ Content );
 / * 
where the code shown below also may be used, 
$ = new new DOM the DOMDocument () ; 
$ the DOM-> Load ($ URL); 
 * / 
 
$ Elements = $ DOM -> the getElementsByTagName ( "current_conditions" );
 $ Element = $ Elements-> Item (0 );
 $ for condition Condition = get_google_xml_data ( $ Element , "for condition Condition" );
 $ temp_c = get_google_xml_data ( $ Element , "temp_c" );
 echo 'weather:', $ for condition Condition , '<br />' ;
 echo 'temperature:', $ temp_c , '<br />' ; 
 
function get_utf8_string ( $ Content ) {     //   number of characters converted into the format utf8 
    $ encoding = mb_detect_encoding ( $ Content , Array ( 'the ASCII', 'UTF-. 8' , 'GB2312', 'GBK', 'BIG5' ));
    return  mb_convert_encoding(Content $ , '. 8-UTF', $ encoding ); 
} 
 
function get_google_xml_data ( $ Element , $ Tagname ) {
     $ Tags = $ Element -> the getElementsByTagName ( $ Tagname );    //   get all the Tagname $ 
 
    $ Tag = $ Tags - > Item (0);   //   get the first named tags to $ Tagname 
    IF ( $ tag -> hasAttributes ()) {     //   Get the data attribute 
        $ attribute = $ tag -> the getAttribute ( "data" );
         return  $ attribute ; 
    } the else {
        return false;
    }
}
?>

   This is just a simple example, includes only the loadXML, item, getAttribute, getElementsByTagName and other methods, there are some useful ways, this based on your actual needs.

[XMLReader]
   When we use php xml content interpretation, there are many items provide functions, so that we do not have a character to a resolution, as long as according to the label and attribute names, you can remove the attribute with the content of the document, compared under a lot of convenience. Which XMLReader sequentially accessed xml files node, the node can be thought of as a cursor through the entire document, and to crawl the content needed.

<?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();
'weather:'echo$condition, '<br />';
echo '温度:', $temp_c, '<br />';

   We just need to take the first condition and a temp_c, then traverse all the nodes, the first condition and a temp_c write variables encountered, the final output.

[DOMXPath]
   This method requires the use of DOMDocument object to create the structure of the entire document,

<?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 'weather:', $ for condition Condition , '<br />' ;
 echo 'temperature:', $ temp_c , '<br />' ; 
 
function get_google_xml_data ( $ Element , $ Tagname ) {
     $ Tags = $ Element -> getElementsByTagName ( $ tagname );    //   get all $ tagname 
 
    $ tag = $ tags -> Item (0);   //   get the first to $ tagname named label 
    IF ( $ tag -> hasAttributes ( )) {     //   Get the data attribute 
        $ 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] )

   The function parses the XML file corresponding to the two arrays, index parameter values array containing the points corresponding to the pointer value. The last two parameters may pass a pointer to an array of functions.
   Note: xml_parse_into_struct () fails to return 0, 1 successful return. This is the TRUE and FALSE are different, for example, to the attention of the operator ===.

<?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]
   This method can be used in PHP5 in
   this example has a relevant official documents in google, as follows:

// UTF-8: Charset 
/ * * 
  * The weather forecast calls google api with php Simplexml, and examples of different official g 
  * google official php domxml for examples google weather forecast 
  * 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, with the city pinyin 
$ city = empty ( $ _GET ? [ 'city']) 'shenzhen': $ _GET [ 'city' ];
 $ Content = file_get_contents ( "http://www.google.com/ig ? / API weather 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;
?>

 

Guess you like

Origin www.cnblogs.com/mzhaox/p/11294317.html