Table of Contents
books.xml file:
Home Backend Development PHP Tutorial Example code for PHP method of reading XML files

Example code for PHP method of reading XML files

Mar 21, 2017 am 09:42 AM

The examples in this article summarize the method of PHP reading XML format files. Share it with everyone for your reference, the details are as follows:

books.xml file:

1

2

3

4

5

6

7

8

9

10

11

12

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

Copy after login
  1. DOMDocument method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

}

?>

Copy after login

2. Use SAX parser to read XML:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

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

}

?>

Copy after login

3. Use regular expression to parse XML:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<?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" );

}

?>

Copy after login

4. Parse XML into array

1

2

3

4

5

6

7

8

9

10

11

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

?>

Copy after login

5. Check whether the XML is valid

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

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

?>

Copy after login

6. Can be used to read XML accurately

test.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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

Copy after login

test. php:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

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

Copy after login

The above is the detailed content of Example code for PHP method of reading XML files. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

See all articles