欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP讀取XML格式文件的方法總結(jié)

 更新時(shí)間:2017年02月27日 12:00:09   作者:小炒花生米  
這篇文章主要介紹了PHP讀取XML格式文件的方法,結(jié)合實(shí)例形式總結(jié)分析了php針對(duì)xml格式文件的讀取、解析、加載、遍歷等操作技巧,需要的朋友可以參考下

本文實(shí)例總結(jié)了PHP讀取XML格式文件的方法。分享給大家供大家參考,具體如下:

books.xml文件:

<books>
<book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>

1.DOMDocument方法

<?php
$doc = new DOMDocument();
$doc->load( 'books.xml' );
$books = $doc->getElementsByTagName( "book" );
foreach( $books as $book )
{
$authors = $book->getElementsByTagName( "author" );
$author = $authors->item(0)->nodeValue;
$publishers = $book->getElementsByTagName( "publisher" );
$publisher = $publishers->item(0)->nodeValue;
$titles = $book->getElementsByTagName( "title" );
$title = $titles->item(0)->nodeValue;
echo "$title - $author - $publisher\n";
echo "<br>";
}
?>

2.用 SAX 解析器讀取 XML:

<?php
$g_books = array();
$g_elem = null;
function startElement( $parser, $name, $attrs ) 
{
global $g_books, $g_elem;
if ( $name == 'BOOK' ) $g_books []= array();
$g_elem = $name;
}
function endElement( $parser, $name ) 
{
global $g_elem;
$g_elem = null;
}
function textData( $parser, $text )
{
global $g_books, $g_elem;
if ( $g_elem == 'AUTHOR' ||
$g_elem == 'PUBLISHER' ||
$g_elem == 'TITLE' )
{
$g_books[ count( $g_books ) - 1 ][ $g_elem ] = $text;
}
}
$parser = xml_parser_create();
xml_set_element_handler( $parser, "startElement", "endElement" );
xml_set_character_data_handler( $parser, "textData" );
$f = fopen( 'books.xml', 'r' );
while( $data = fread( $f, 4096 ) )
{
xml_parse( $parser, $data );
}
xml_parser_free( $parser );
foreach( $g_books as $book )
{
echo $book['TITLE']." - ".$book['AUTHOR']." - ";
echo $book['PUBLISHER']."\n";
}
?>

3.用正則表達(dá)式解析 XML:

<?php
$xml = "";
$f = fopen( 'books.xml', 'r' );
while( $data = fread( $f, 4096 ) ) {
  $xml .= $data; 
}
fclose( $f );
preg_match_all( "/\<book\>(.*?)\<\/book\>/s", $xml, $bookblocks );
foreach( $bookblocks[1] as $block )
{
preg_match_all( "/\<author\>(.*?)\<\/author\>/", $block, $author );
preg_match_all( "/\<title\>(.*?)\<\/title\>/",  $block, $title );
preg_match_all( "/\<publisher\>(.*?)\<\/publisher\>/", $block, $publisher );
echo( $title[1][0]." - ".$author[1][0]." - ".$publisher[1][0]."\n" );
}
?>

4.解析XML到數(shù)組

<?php
  $data = "<root><line /><content language=\"gb2312\">簡(jiǎn)單的XML數(shù)據(jù)</content></root>";
  $parser = xml_parser_create(); //創(chuàng)建解析器
  xml_parse_into_struct($parser, $data, $values, $index); //解析到數(shù)組
  xml_parser_free($parser); //釋放資源
  //顯示數(shù)組結(jié)構(gòu)
  echo "\n索引數(shù)組\n";
  print_r($index);
  echo "\n數(shù)據(jù)數(shù)組\n";
  print_r($values);
?>

5.檢查XML是否有效

<?php
  //創(chuàng)建XML解析器
  $xml_parser = xml_parser_create();
  //使用大小寫折疊來保證能在元素?cái)?shù)組中找到這些元素名稱
  xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
  //讀取XML文件
  $xmlfile = "bb.xml";
  if (!($fp = fopen($xmlfile, "r")))
  {
    die("無法讀取XML文件$xmlfile");
  }
  //解析XML文件
  $has_error = false;      //標(biāo)志位
  while ($data = fread($fp, 4096))
  {
    //循環(huán)地讀入XML文檔,只到文檔的EOF,同時(shí)停止解析
    if (!xml_parse($xml_parser, $data, feof($fp)))
    {
      $has_error = true;
      break;
    }
  }
  if($has_error)
  { 
    echo "該XML文檔是錯(cuò)誤的!<br />";
    //輸出錯(cuò)誤行,列及其錯(cuò)誤信息
    $error_line  = xml_get_current_line_number($xml_parser);
    $error_row  = xml_get_current_column_number($xml_parser);
    $error_string = xml_error_string(xml_get_error_code($xml_parser));
    $message = sprintf("[第%d行,%d列]:%s", 
            $error_line,
            $error_row,
            $error_string);
    echo $message;
  }
  else
  {
    echo "該XML文檔是結(jié)構(gòu)良好的。";
  }
  //關(guān)閉XML解析器指針,釋放資源
  xml_parser_free($xml_parser);
?>

6.可用于精確的讀取XML

test.xml

<?xml version="1.0" encoding="UTF-8" ?>
  <SBMP_MO_MESSAGE>
    <CONNECT_ID>100</CONNECT_ID>
    <MO_MESSAGE_ID>123456</MO_MESSAGE_ID>
    <RECEIVE_DATE>20040605</RECEIVE_DATE>
    <RECEIVE_TIME>153020</RECEIVE_TIME>
    <GATEWAY_ID>1</GATEWAY_ID>
    <VALID>1</VALID>
    <CITY_CODE>010</CITY_CODE>
    <CITY_NAME>北京</CITY_NAME>
    <STATE_CODE>010</STATE_CODE>
    <STATE_NAME>北京</STATE_NAME>
    <TP_PID>0</TP_PID>
    <TP_UDHI>0</TP_UDHI>
    <MSISDN>15933626501</MSISDN>
    <MESSAGE_TYPE>8</MESSAGE_TYPE>
    <MESSAGE>5618常年供應(yīng)苗木,品種有玉蘭、黃葉楊等。聯(lián)系人:張三,電話:1234567890。</MESSAGE>
    <LONG_CODE>100</LONG_CODE>
    <SERVICE_CODE>9588</SERVICE_CODE>
  </SBMP_MO_MESSAGE>

test.php:

<?php
$myData = array();
$file = file_get_contents("test.xml");
if(strpos($file, '<?xml') > -1) {
    try {
      //加載解析xml
      $xml = simplexml_load_string($file);
      if($xml) {
        //echo $this->result;
        //獲取節(jié)點(diǎn)值
        $CONNECT_ID = $xml->CONNECT_ID;
        $MO_MESSAGE_ID = $xml->MO_MESSAGE_ID;
        $RECEIVE_DATE = $xml->RECEIVE_DATE;
        $RECEIVE_TIME = $xml->RECEIVE_TIME;
        $GATEWAY_ID = $xml->GATEWAY_ID;
        $VALID = $xml->VALID;
        $CITY_CODE = $xml->CITY_CODE;
        $CITY_NAME = $xml->CITY_NAME;
        $STATE_CODE = $xml->CITY_CODE;
        $STATE_NAME = $xml->STATE_NAME;
        $TP_PID = $xml->TP_PID;
        $TP_UDHI = $xml->TP_UDHI;
        $MSISDN = $xml->MSISDN;
        $MESSAGE_TYPE = $xml->MESSAGE_TYPE;
        $MESSAGE = $xml->MESSAGE;//短信
        $LONG_CODE = $xml->LONG_CODE;
        $SERVICE_CODE = $xml->SERVICE_CODE;
        preg_match("/(561)\d{1,2}/", $MESSAGE, $code);
        switch($code[0]) {
          case 5618 :
            $myData[message] = $MESSAGE;
            break;
          default :
            $myData[] = '沒有短消息。';
            break;
          }
        } else {
          echo "加載xml文件錯(cuò)誤。";
        }
    } catch(exception $e){
      print_r($e);
    }
} else {
  echo "沒有該XML文件。";
}
echo "<pre>";
print_r($myData);
echo "<hr>";
echo $myData[message];
?>

PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:

在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson

在線格式化XML/在線壓縮XML
http://tools.jb51.net/code/xmlformat

XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP針對(duì)XML文件操作技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《PHP錯(cuò)誤與異常處理方法總結(jié)》、《PHP基本語法入門教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論