Home Backend Development XML/RSS Tutorial How to use XML and YAML

How to use XML and YAML

Dec 24, 2016 am 11:03 AM

Recently, I was processing some configuration files and came across files in YAML format. Because I have never been exposed to files in this format before, I am relatively familiar with XML. So what is YAML? What are its advantages and disadvantages compared to XML? When should YAML be used? How to use YAML? Let’s make a brief summary here. Let’s start with XML.

I believe everyone is familiar with XML. Below are conceptual things I extracted from the Internet. You can take a look. Not much to say here. Let’s talk more about some basic usage.
XML overview:
Extensible Markup Language (XML), a markup language used to mark electronic documents to make them structural. It can be used to mark data and define data types. It is a markup language that allows users to mark up their own The source language in which the language is defined. XML is a subset of Standard Generalized Markup Language (SGML) and is well suited for Web transport. XML provides a unified method for describing and exchanging structured data independent of applications or vendors.
Format characteristics:
XML is different from databases such as Access, Oracle and SQL Server. Databases provide more powerful data storage and analysis capabilities, such as data indexing, sorting, search, related consistency, etc. XML only stores data. In fact, the biggest difference between XML and other data representations is that it is extremely simple. This is a seemingly trivial advantage, but it is what makes XML unique.
The design difference between XML and HTML is: XML is designed to transmit and store data, and its focus is the content of the data. While HTML is designed to display data, its focus is on the appearance of the data. HTML is designed to display information, while XML is designed to transmit information.
Differences in syntax between XML and HTML: Not all HTML tags need to appear in pairs, while XML requires that all tags must appear in pairs; HTML tags are not case-sensitive, while XML is case-sensitive.
Reading and writing:
There are two ways I am familiar with to read and write XML. One is to obtain the XML value through JavaScript, and the other is to read it with PHP. You can refer to the manual when writing XML. The XML format is relatively free and you can customize tags, but one principle is to be intuitive. Examples are listed below for everyone to test. If you have any questions, you can communicate.

note.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
  <from>John</from>
  <to>George</to>
  <message>Don&#39;t forget the meeting!</message>
</note>
Copy after login

xml_test.html
JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmls="http://www.w3.org/1999/xhtml">
<body>
  <p>
    <b>To:</b> <span id="to"></span><br />
    <b>From:</b> <span id="from"></span><br />
    <b>Message:</b> <span id="message"></span>
  </p>
<script type="text/javascript">
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET","note.xml",false);
  xmlhttp.send();
  xmlDoc=xmlhttp.responseXML;

  document.getElementById("to").innerHTML=
  xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
  document.getElementById("from").innerHTML=
  xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
  document.getElementById("message").innerHTML=
  xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
</script>

</body>
</html>
Copy after login

xml_test.php

<?php 
//创建DOM对象
$xml = new DOMDocument(); 
//读取XML文件
$xml = simplexml_load_file(&#39;note.xml&#39;); 
//输出XML文件中from属性,多个相同属性也就是数组的形式,可以用下标来取值
echo $xml->from;
?>
Copy after login

YAML Introduction:
YAML is increasingly used as a serialization language that is simpler and easier to read than XML. in the development of applications and configuration files. This article will briefly introduce the current status of YAML, the advantages and disadvantages of YAML compared with XML, and give typical application scenarios of YAML and how to use it (covering c/c++, ruby, PHP, etc.) through practical examples.
Advantages:
YAML has good readability.
YAML and scripting languages ​​have good interactivity.
YAML uses data types that implement the language.
YAML has a consistent information model.
YAML is easy to implement.
The above 5 items are the shortcomings of XML. At the same time, YAML also has the following advantages of XML:
YAML can be processed based on streams;
YAML has strong expression ability and good scalability.
In short, YAML attempts to use a more agile way than XML to complete the tasks completed by XML.
For more content and specifications, please see http://www.yaml.org.
Syntax:
Structure is displayed through spaces. Items in Sequence are represented by "-", and key-value pairs in Map are separated by ":".
This is almost all the syntax.
For example...
Generally, YAML files have the extension .yaml. For example: john.yaml

name: John Smith

age: 37

spouse:

name: Jane Smith

age: 25

children:

- name: Jimmy Smith

age: 15

- name: Jenny Smith

age 12
Copy after login

John is 37 years old and has a happy family of four. The two children, Jimmy and Jenny, are lively and cute. His wife Jane is young and beautiful.
If you study in depth, you may also find some social problems^_^.
It can be seen that the readability of YAML is good.
Reading and writing:
For reading and writing YAML in PHP, I recommend using the Spyc class to read and write YAML files.
Spyc class file download address:
https://github.com/mustangostang/spyc/

Spyc has only 2 class methods available, one is to read YAML files, and the other is to generate YAML file format. The two methods are introduced below.

include(&#39;spyc.php&#39;);

// 读取YAML文件,生成数组
$yaml = Spyc::YAMLLoad(&#39;spyc.yaml&#39;);

// 将数组转换成YAML文件
$array[&#39;name&#39;]  = &#39;andy&#39;;
$array[&#39;site&#39;] = &#39;21andy.com&#39;;
$yaml = Spyc::YAMLDump($array);
Copy after login

php.ini reads the ini parsing method and that configuration cannot support multi-dimensional arrays. So, I am very interested in yaml to generate multi-dimensional arrays. I mainly want to make a configuration file, as follows:

  - { row: 0, col: 0, func: {tx: [0, 1]} }
Copy after login

convert to php multi-dimensional arrays As follows:
test.yaml (this example is my DB configuration file, highly recommended!)

DB:
  default:
    dsn: &#39;mysql:dbname=test;host=127.0.0.1&#39;
    user: &#39;root&#39;
    pass: &#39;111&#39;
  session:
    dsn: &#39;mysql:dbname=test;host=127.0.0.1&#39;
    user: &#39;root&#39;
    pass: &#39;111&#39;
Copy after login

test.php

<?php
include(&#39;spyc.php&#39;);
//读取YAML文件,生成数组
$yaml = Spyc::YAMLLoad(&#39;test.yaml&#39;);
echo "<pre class="brush:php;toolbar:false">";
print_r($yaml);
echo "
"; PHP code Array ( [DB] => Array ( [default] => Array ( [dsn] => mysql:dbname=test;host=127.0.0.1 [user] => root [pass] => 111 ) [session] => Array ( [dsn] => mysql:dbname=test;host=127.0.0.1 [user] => root [pass] => 111 ) ) )
Copy after login

Example of PHP generated YAML file:
include('spyc.php') ;
//Convert the array into YAML file format
$array['name'] = 'PHP Programmer's Notes';
$array['site'] = 'www.songchaoke.cn';
$yaml = Spyc ::YAMLDump($array);
//Write the converted YAML to the file
$f = fopen('test2.yaml',"w+");
fwrite($f,$yaml);
fclose( $f);
[/code]

For more articles related to the use of XML and YAML, please pay attention to 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 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)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

How to convert XML to PDF on your phone? How to convert XML to PDF on your phone? Apr 02, 2025 pm 10:18 PM

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

How to open web.xml How to open web.xml Apr 03, 2025 am 06:51 AM

To open a web.xml file, you can use the following methods: Use a text editor (such as Notepad or TextEdit) to edit commands using an integrated development environment (such as Eclipse or NetBeans) (Windows: notepad web.xml; Mac/Linux: open -a TextEdit web.xml)

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to export pdf with xml How to export pdf with xml Apr 03, 2025 am 06:45 AM

There are two ways to export XML to PDF: using XSLT and using XML data binding libraries. XSLT: Create an XSLT stylesheet, specify the PDF format to convert XML data using the XSLT processor. XML Data binding library: Import XML Data binding library Create PDF Document object loading XML data export PDF files. Which method is better for PDF files depends on the requirements. XSLT provides flexibility, while the data binding library is simple to implement; for simple conversions, the data binding library is better, and for complex conversions, XSLT is more suitable.

See all articles