How to use XML and YAML

高洛峰
Release: 2016-12-24 11:03:01
Original
1470 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template