Home Backend Development PHP Tutorial How PHP encapsulates XML

How PHP encapsulates XML

May 17, 2018 am 11:52 AM
php how encapsulation

This article mainly introduces how PHP encapsulates XML, and combines it with a complete example to analyze the encapsulation and usage of PHP's related operating techniques for loading, reading and writing xml files. Friends in need can refer to the following

The details are as follows:

xml_dom.php encapsulation class file:

<?php
/**
 * Class xml_dom
 *
nodeType:
1 XML_ELEMENT_NODE(元素类型)
2 XML_ATTRIBUTE_NODE
3 XML_TEXT_NODE
4 XML_CDATA_SECTION_NODE
5 XML_ENTITY_REFERENCE_NODE
6 XML_ENTITY_NODE
7 XML_PROCESSING_INSTRUCTION_NODE
8 XML_COMMENT_NODE(注释类型)
9 XML_DOCUMENT_NODE
10 XML_DOCUMENT_TYPE_NODE
11 XML_DOCUMENT_FRAGMENT_NODE
12 XML_NOTATION_NODE
 *
PHP DOMDocument操作:
属性:
Attributes   存储节点的属性列表(只读)
childNodes   存储节点的子节点列表(只读)
dataType   返回此节点的数据类型
Definition   以DTD或XML模式给出的节点的定义(只读)
Doctype   指定文档类型节点(只读)
documentElement   返回文档的根元素(可读写)
firstChild   返回当前节点的第一个子节点(只读)
Implementation   返回XMLDOMImplementation对象
lastChild   返回当前节点最后一个子节点(只读)
nextSibling   返回当前节点的下一个兄弟节点(只读)
nodeName   返回节点的名字(只读)
nodeType   返回节点的类型(只读)
nodeTypedValue   存储节点值(可读写)
nodeValue   返回节点的文本(可读写)
ownerDocument   返回包含此节点的根文档(只读)
parentNode   返回父节点(只读)
Parsed   返回此节点及其子节点是否已经被解析(只读)
Prefix   返回名称空间前缀(只读)
preserveWhiteSpace   指定是否保留空白(可读写)
previousSibling   返回此节点的前一个兄弟节点(只读)
Text   返回此节点及其后代的文本内容(可读写)
url   返回最近载入的XML文档的URL(只读)
Xml   返回节点及其后代的XML表示(只读)
方法:
appendChild   为当前节点添加一个新的子节点,放在最后的子节点后
cloneNode   返回当前节点的拷贝
createAttribute   创建新的属性
createCDATASection   创建包括给定数据的CDATA段
createComment   创建一个注释节点
createDocumentFragment   创建DocumentFragment对象
createElement   创建一个元素节点
createEntityReference   创建EntityReference对象
createNode   创建给定类型,名字和命名空间的节点
createPorcessingInstruction   创建操作指令节点
createTextNode   创建包括给定数据的文本节点
getElementsByTagName   返回指定名字的元素集合
hasChildNodes   返回当前节点是否有子节点
insertBefore   在指定节点前插入子节点
Load   导入指定位置的XML文档
loadXML   导入指定字符串的XML文档
removeChild   从子结点列表中删除指定的子节点
replaceChild   从子节点列表中替换指定的子节点
Save   把XML文件存到指定节点
selectNodes   对节点进行指定的匹配,并返回匹配节点列表
selectSingleNode   对节点进行指定的匹配,并返回第一个匹配节点
transformNode   使用指定的样式表对节点及其后代进行转换
 *
 */
class xml_dom
{
  protected $dblink; // xml连接
  protected $dbfile; // xml文件路径
  /**
   * xml文件 构造类
   * @param $db_file xml文件
   */
  public function __construct($db_file)
  {
    $this->dbfile = $db_file;
    if(!file_exists($db_file))
    {
//     die(&#39;未找到数据库文件&#39;);
      $this->dblink = new DOMDocument(&#39;1.0&#39;, &#39;utf-8&#39;);
      $root = $this->dblink->createElement(&#39;root&#39;);
      $this->dblink->appendChild($root);
      $this->dblink->formatOutput = true;  // xml文件保留缩进样式
      $this->dblink->save($this->dbfile);
    }
    else
    {
      $this->dblink = new DOMDocument();
      $this->dblink->formatOutput = true;
      $this->dblink->load($this->dbfile);
    }
  }
  /**
   * 遍历所有元素
   * ===============================================
   * 标准xml文件,一个元素可能有n个属性,可用自定义键[nodevalue]获取元素值
   * <?xml version="1.0" encoding="utf-8"?>
   * <table name="posts">
   *   <column name="id">1</column>
   *   <column name="title">标题一</column>
   *   <column name="content">详细内容一</column>
   * </table>
   * ===============================================
   * 简单xml文件,没有属性,键值一一对应
   * <?xml version="1.0" encoding="utf-8"?>
   * <root>
   *   <posts>
   *     <id>1</id>
   *     <title>标题一</title>
   *     <content>详细内容一</content>
   *   </posts>
   * </root>
   * @param $node
   * @return array
   */
  function getData($node=0){
    if(!$node)
    {
      $node = $this->dblink->documentElement;
    }
    $array = array();
    foreach($node->attributes as $attribute)
    {
      $key = $attribute->nodeName;
      $val = $attribute->nodeValue;
      $array[$key] = $val;
    }
    if(count($array))  // 有属性,则用[nodevalue]键代表值
    {
      $array[&#39;nodevalue&#39;] = $node->nodeValue;
    }
    // 递归遍历所有子元素
    $node_child = $node->firstChild;
    while($node_child)
    {
      if(XML_ELEMENT_NODE == $node_child->nodeType)
      {
        $tagname = $node_child->tagName;
        $result = $this->getData($node_child);
        if(isset($array[$tagname])) // 发现有重复tagName的子元素存在,所以改用数组存储重复tagName的所有子元素
        {
          if(!is_array($array[$tagname][0]))
          {
            $tmp = $array[$tagname];
            $array[$tagname] = array();
            $array[$tagname][] = $tmp;
          }
          $array[$tagname][] = $result;
        }
        else
        {
          $array[$tagname] = $result;
        }
      }
      $node_child = $node_child->nextSibling;
    }
    if(!count($array)) // 没有子元素&没有属性=最末子元素,就返回该元素的nodeValue值
    {
      return $node->nodeValue;
    }
    return $array;
  }
  /**
   * 把array数据写到xml文件(覆盖)
   * @param $data
   */
  public function setData($data,&$node=0)
  {
    $is_root = false;
    if(!$node)
    {
      $is_root = true;
      $node = $this->dblink->documentElement;
      // 清除原数据
      $remove = array();
      $node_child = $node->firstChild;
      while($node_child)
      {
        $remove[] = $node_child;
        $node_child = $node_child->nextSibling;
      }
      foreach($remove as $r)
      {
        $node->removeChild($r);
      }
    }
    if(is_array($data))
    {
      foreach($data as $k=>$v)
      {
        if(is_array($v))
        {
          foreach($v as $r)
          {
            $item = $this->dblink->createElement($k);
            $result = $this->setData($r,$item);
            $node->appendChild($result);
          }
        }
        else
        {
          $item = $this->dblink->createElement($k);
          $value = $this->dblink->createTextNode($v);
          $item->appendChild($value);
          $node->appendChild($item);
        }
      }
    }
    else
    {
      $item = $this->dblink->createTextNode($data);
      $node->appendChild($item);
    }
    if($is_root)
    {
      $this->dblink->save($this->dbfile);  // 覆盖写入
    }
    else
    {
      return $node;
    }
  }
}
Copy after login

A simple usage example is as follows:

smp.xml file:

<?xml version="1.0" encoding="utf-8"?>
<root>
   <posts>
     <id>1</id>
     <title>标题一</title>
     <content>详细内容一</content>
   </posts>
   <posts>
     <id>2</id>
     <title>标题二</title>
     <content>详细内容二</content>
   </posts>
   <posts>
     <id>3</id>
     <title>标题三</title>
     <content>详细内容三</content>
   </posts>
</root>
Copy after login

index.php file:

include("xml_dom.php");
$xml=new xml_dom("smp.xml");//载入xml文件
$xmlarr=$xml->getData();//读取xml文件内容
var_dump($xmlarr);
Copy after login

Run Result:

array(1) {
 ["posts"]=>
 array(3) {
  [0]=>
  array(3) {
   ["id"]=>
   string(1) "1"
   ["title"]=>
   string(9) "标题一"
   ["content"]=>
   string(15) "详细内容一"
  }
  [1]=>
  array(3) {
   ["id"]=>
   string(1) "2"
   ["title"]=>
   string(9) "标题二"
   ["content"]=>
   string(15) "详细内容二"
  }
  [2]=>
  array(3) {
   ["id"]=>
   string(1) "3"
   ["title"]=>
   string(9) "标题三"
   ["content"]=>
   string(15) "详细内容三"
  }
 }
}
Copy after login

Related recommendations:

Detailed explanation of PHP implementation of parsing xml into array case

jQuery traversal of XML nodes and attributes implementation steps

Explanation of examples of XML in AJAX

The above is the detailed content of How PHP encapsulates XML. 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
1 months 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
The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

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.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

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.

Using Laravel: Streamlining Web Development with PHP Using Laravel: Streamlining Web Development with PHP Apr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

PHP and IIS: Making Them Work Together PHP and IIS: Making Them Work Together Apr 21, 2025 am 12:06 AM

Configuring and running PHP on IIS requires the following steps: 1) Download and install PHP, 2) Configuring IIS and adding FastCGI module, 3) Create and set up an application pool, 4) Create a website and bind to an application pool. Through these steps, you can easily deploy PHP applications on your Windows server and improve application stability and efficiency by configuring scaling and optimizing performance.

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.

See all articles