首頁 > 後端開發 > php教程 > PHP實作讀取XML格式檔案的方法

PHP實作讀取XML格式檔案的方法

墨辰丷
發布: 2023-03-27 22:00:01
原創
2992 人瀏覽過

這篇文章主要介紹了PHP讀取XML格式檔案的方法,結合實例形式總結分析了php針對xml格式檔案的讀取、解析、載入、遍歷等操作技巧,需要的朋友可以參考下

具體如下:

books.xml檔:

<books>
<book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O&#39;Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O&#39;Reilly</publisher>
</book>
</books>
登入後複製

1.DOMDocument方法

<?php
$doc = new DOMDocument();
$doc->load( &#39;books.xml&#39; );
$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 == &#39;BOOK&#39; ) $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 == &#39;AUTHOR&#39; ||
$g_elem == &#39;PUBLISHER&#39; ||
$g_elem == &#39;TITLE&#39; )
{
$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( &#39;books.xml&#39;, &#39;r&#39; );
while( $data = fread( $f, 4096 ) )
{
xml_parse( $parser, $data );
}
xml_parser_free( $parser );
foreach( $g_books as $book )
{
echo $book[&#39;TITLE&#39;]." - ".$book[&#39;AUTHOR&#39;]." - ";
echo $book[&#39;PUBLISHER&#39;]."\n";
}
?>
登入後複製

3.用正規表示式解析XML:

<?php
$xml = "";
$f = fopen( &#39;books.xml&#39;, &#39;r&#39; );
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到陣列

#

<?php
  $data = "<root><line /><content language=\"gb2312\">简单的XML数据</content></root>";
  $parser = xml_parser_create(); //创建解析器
  xml_parse_into_struct($parser, $data, $values, $index); //解析到数组
  xml_parser_free($parser); //释放资源
  //显示数组结构
  echo "\n索引数组\n";
  print_r($index);
  echo "\n数据数组\n";
  print_r($values);
?>
登入後複製


5.檢查XML是否有效

<?php
  //创建XML解析器
  $xml_parser = xml_parser_create();
  //使用大小写折叠来保证能在元素数组中找到这些元素名称
  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;      //标志位
  while ($data = fread($fp, 4096))
  {
    //循环地读入XML文档,只到文档的EOF,同时停止解析
    if (!xml_parse($xml_parser, $data, feof($fp)))
    {
      $has_error = true;
      break;
    }
  }
  if($has_error)
  { 
    echo "该XML文档是错误的!<br />";
    //输出错误行,列及其错误信息
    $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文档是结构良好的。";
  }
  //关闭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常年供应苗木,品种有玉兰、黄叶杨等。联系人:张三,电话: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, &#39;<?xml&#39;) > -1) {
    try {
      //加载解析xml
      $xml = simplexml_load_string($file);
      if($xml) {
        //echo $this->result;
        //获取节点值
        $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[] = &#39;没有短消息。&#39;;
            break;
          }
        } else {
          echo "加载xml文件错误。";
        }
    } catch(exception $e){
      print_r($e);
    }
} else {
  echo "没有该XML文件。";
}
echo "<pre class="brush:php;toolbar:false">";
print_r($myData);
echo "<hr>";
echo $myData[message];
?>
登入後複製

以上就是本文的全部內容,希望對大家的學習有幫助。

相關推薦:#########PHP實作###讀取xml###檔案的方法########## ######php讀取XML的常見方法實例總結_php技巧############jQuery解析讀取XML檔案方法(附程式碼)########## ##################

以上是PHP實作讀取XML格式檔案的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板