search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

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't forget the meeting!</message>
</note>

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>

xml_test.php

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

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

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('spyc.php');

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

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

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

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

DB:
  default:
    dsn: 'mysql:dbname=test;host=127.0.0.1'
    user: 'root'
    pass: '111'
  session:
    dsn: 'mysql:dbname=test;host=127.0.0.1'
    user: 'root'
    pass: '111'

test.php

<?php
include('spyc.php');
//读取YAML文件,生成数组
$yaml = Spyc::YAMLLoad('test.yaml');
echo "<pre>";
print_r($yaml);
echo "</pre>";
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
                )

        )

)

Example of PHP generated YAML file:
<?php
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

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

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)

How to install the XML Tools plugin in Notepad  ? (Plugin Manager) How to install the XML Tools plugin in Notepad ? (Plugin Manager) Mar 05, 2026 am 12:37 AM

Notepad v8.6.1 has completely removed the PluginManager. XMLTools cannot be installed because it has not been migrated to the new plug-in system and the author has stopped updating it. Manual installation is only applicable to v8.5.7 and earlier versions. It is recommended to use built-in functions or alternatives such as VSCode.

How to convert XML to YAML for DevOps? (Configuration Management) How to convert XML to YAML for DevOps? (Configuration Management) Mar 12, 2026 am 12:11 AM

xmltodict PyYAMListhesafestcomboforDevOpsconfigfilesbecauseitpreservescomments,CDATA,namespaces,andattributesaccurately,unlikerawXML-to-YAMLtoolsorCLIutilitieslikeyqandxmllintwhichsilentlydropcriticalmetadata.

How to format and beautify XML code in Notepad  ? (Pretty Print) How to format and beautify XML code in Notepad ? (Pretty Print) Mar 07, 2026 am 12:20 AM

Notepad needs to manually install and enable the XMLTools plug-in to format XML; if the tags are messed up or the content is lost after formatting, it means that the XML itself is illegal, and there are problems such as unclosed tags or illegal characters.

How to convert an XML file to a Word document? (Reporting) How to convert an XML file to a Word document? (Reporting) Mar 09, 2026 am 01:05 AM

python-docx does not support direct reading of XML files. You need to use xml.etree.ElementTree or lxml to parse the XML extraction fields first, and then write them into the Document object segment by segment. Explicit declaration of prefixes is required to process namespaces, and manual manipulation of the underlying XML is required for table merging and styling. Chinese paths should be avoided when saving.

How to minify XML files for faster web loading? (Performance Optimization) How to minify XML files for faster web loading? (Performance Optimization) Mar 08, 2026 am 12:16 AM

RunningminifyonXMLwithoutunderstandingitsrulesbreaksparsingoralterssemanticsbecausewhitespacecanbemeaningful;safeminificationrequiresdata-orientedXML,controlledgeneration/consumption,andstrictparserawareness.

How to use Attributes vs Elements in XML? (Design Best Practices) How to use Attributes vs Elements in XML? (Design Best Practices) Mar 16, 2026 am 12:26 AM

You should use attributes to store short metadata (such as id, type), and use elements to store scalable content data; because attributes do not support namespaces, duplication, nesting, and internationalization, their parsing is error-prone and maintenance is difficult.

How to parse XML data from a URL API? (Rest Services) How to parse XML data from a URL API? (Rest Services) Mar 13, 2026 am 12:06 AM

To parse remote XML API in Python, you need to use requests to get the response and then check the status code and Content-Type. Prioritize using r.text with xml.etree.ElementTree to parse; when encountering a namespace, you need to pass the namespace dictionary; use iterparse to stream large files and clear them manually; front-end JS requires CORS support or proxy.

How to open and view XML files in Windows 11? (Beginner Guide) How to open and view XML files in Windows 11? (Beginner Guide) Mar 12, 2026 am 01:02 AM

The XML file cannot be opened by double-clicking because it is associated with Notepad by default, causing confusion in the display. You should use Notepad, VSCode or Edge instead; Edge can format and report errors, while VSCode requires the installation of extensions such as RedHatXML for normal highlighting, indentation and verification.

Related articles