Home Backend Development PHP Tutorial An explanation of the php XML file interpretation class

An explanation of the php XML file interpretation class

Jun 11, 2018 pm 01:42 PM
php xml

XMLParser.class.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

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

<?php

/** XML 文件分析类

*   Date:   2013-02-01

*   Author: fdipzone

*   Ver:    1.0

*

*   func:

*   loadXmlFile($xmlfile)     读入xml文件输出Array

*   loadXmlString($xmlstring) 读入xmlstring 输出Array

*/

class XMLParser{

    /** 读取xml文件

    * @param  String  $xmlfile

    * @return Array

    */

    public function loadXmlFile($xmlfile){

        // get xmlfile content

        $xmlstring = file_exists($xmlfile)? file_get_contents($xmlfile) : &#39;&#39;;

        // parser xml

        list($flag, $data) = $this->parser($xmlstring);

        return $this->response($flag, $data);

    }

    /** 读取xmlstring

    * @param  String $xmlstring

    * @return Array

    */

    public function loadXmlString($xmlstring){

        // parser xml

        list($flag, $data) = $this->parser($xmlstring);

        return $this->response($flag, $data);

    }

    /** 解释xml内容

    * @param   String $xmlstring

    * @return  Array

    */

    private function parser($xmlstring){

        $flag = false;

        $data = array();

        // check xml format

        if($this->checkXmlFormat($xmlstring)){

            $flag = true;

             

            // xml to object

            $data = simpleXML_load_string($xmlstring, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);

             

            // object to array

            $this->objectToArray($data);

        }

        return array($flag, $data);

    }

    /** 检查xml格式是否正确

    * @param  String $xmlstring

    * @return boolean

    */

    private function checkXmlFormat($xmlstring){

         

        if($xmlstring==&#39;&#39;){

            return false;

        }

        $xml_parser_obj = xml_parser_create();

        if(xml_parse_into_struct($xml_parser_obj, $xmlstring, $vals, $indexs)===1){ // 1:success 0:fail

            return true;

        }else{

            return false;

        }

    }

    /** object 转 Array

    * @param  object $object

    * @return Array

    */

    private function objectToArray(&$object){

         

        $object = (array)$object;

         

        foreach($object as $key => $value){

            if($value==&#39;&#39;){

                $object[$key] = "";

            }else{

                if(is_object($value) || is_array($value)){

                    $this->objectToArray($value);

                    $object[$key] = $value;

                }

            }

        }

     

    }

    /** 输出返回

    * @param  boolean $flag true:false

    * @param  Array   $data 转换后的数据

    * @return Array

    */

    private function response($flag=false, $data=array()){

     

        return array($flag, $data);

     

    }

}

?>

Copy after login

Demo:

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

<?php

require "XMLParser.class.php";

$xmlfile = &#39;file.xml&#39;;

$xmlstring = &#39;<?xml version="1.0" encoding="utf-8"?>

<xmlroot>

<status>1000</status>

<info></info>

<result><id>100</id>

<name>fdipzone</name>

<gender>1</gender>

<age>28</age>

</result>

</xmlroot>&#39;;

echo &#39;<pre class="brush:php;toolbar:false">&#39;;

$xml_parser = new XMLParser();

echo "response xmlfile\r\n";

list($flag, $xmldata) = $xml_parser->loadXmlFile($xmlfile);

if($flag){

print_r($xmldata);

}

echo "response xmlstring\r\n";

list($flag, $xmldata) = $xml_parser->loadXmlString($xmlstring);

if($flag){

print_r($xmldata);

}

echo &#39;

'; ?>
Copy after login

This article explains the php XML file interpretation class. For more related content, please pay attention to the php Chinese website.

Related recommendations:

php CSS Update Class related content explanation

About php __call and __callStatic content explanation

About memcached common commands and usage instructions

The above is the detailed content of An explanation of the php XML file interpretation class. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

XML's Advantages in RSS: A Technical Deep Dive XML's Advantages in RSS: A Technical Deep Dive Apr 23, 2025 am 12:02 AM

XML has the advantages of structured data, scalability, cross-platform compatibility and parsing verification in RSS. 1) Structured data ensures consistency and reliability of content; 2) Scalability allows the addition of custom tags to suit content needs; 3) Cross-platform compatibility makes it work seamlessly on different devices; 4) Analytical and verification tools ensure the quality and integrity of the feed.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

RSS in XML: Unveiling the Core of Content Syndication RSS in XML: Unveiling the Core of Content Syndication Apr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

RSS in XML: Decoding Tags, Attributes, and Structure RSS in XML: Decoding Tags, Attributes, and Structure Apr 24, 2025 am 12:09 AM

RSS is an XML-based format used to publish and subscribe to content. The XML structure of an RSS file includes a root element, an element, and multiple elements, each representing a content entry. Read and parse RSS files through XML parser, and users can subscribe and get the latest content.

See all articles