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 parse XML in Ruby on Rails? (Web Frameworks) How to parse XML in Ruby on Rails? (Web Frameworks) Jan 05, 2026 am 12:53 AM

UseNokogiriforfast,robustXMLparsinginRails:installviagem'nokogiri',parsewithNokogiri::XML,handleencoding/namespacesexplicitly,andextractdatasafelyusingcss()/xpath()whilecheckingdoc.errorsand.textguards.

How to compare two XML files and find differences How to compare two XML files and find differences Jan 05, 2026 am 01:05 AM

Use tools or programming methods to compare XML file differences: first use online tools (such as xmlcompare.org) or IDE plug-ins for visual comparison, and then implement automated analysis through the command line (such as xmllint diff) or Python scripts (using the lxml library to parse and standardize XML). Pay attention to the processing of whitespace characters, attribute order, namespace prefixes and other influencing factors. It is recommended to use CanonicalXML to eliminate format differences.

How to work with XML attributes in Python's ElementTree How to work with XML attributes in Python's ElementTree Jan 01, 2026 am 05:52 AM

XML attributes in ElementTree are operated through the attrib dictionary of the element. They can be safely obtained with get(), modified or added with set(), deleted with pop() or del, and XPath syntax is supported to find elements by attributes.

How to Handle SOAP Faults in XML Web Services How to Handle SOAP Faults in XML Web Services Jan 01, 2026 am 05:00 AM

UnderstandtheSOAPFaultstructure:Itincludesfaultcode,faultstring,optionalfaultactor,andoptionaldetailforerrorspecifics.2.Ontheclientside,catchappropriateexceptionslikeSOAPFaultExceptionorSoapException.3.Extractandprocessdetailinformationforactionablei

How to fix XML encoding issues (UTF-8)? (Character Sets) How to fix XML encoding issues (UTF-8)? (Character Sets) Jan 03, 2026 am 02:48 AM

XMLshowsgarbledtextwhendeclaredUTF-8encodingmismatchesactualbyteencoding;verifywithfile-iorxxd,fixbyresavingcorrectly,andparseinbinarymodetohonortheXMLdeclaration.

How to serialize C# objects to XML? (Data Persistence) How to serialize C# objects to XML? (Data Persistence) Jan 04, 2026 am 01:41 AM

XmlSerializerisidealforsimple,attribute-drivenXMLserializationinC#,requiringpublicproperties,parameterlessconstructors,andconcretetypes;itignores[Serializable],supportsListbutnotDictionary,lackscircularreferencehandling,andneedsexplicitnull/namespace

The Role of XML in modern configuration files (e.g., pom.xml, web.config) The Role of XML in modern configuration files (e.g., pom.xml, web.config) Jan 02, 2026 am 12:59 AM

XMLremainswidelyusedinmodernconfigurationfilesduetoitsstructured,hierarchicaldatarepresentation,enablingclearparent-childrelationshipsandmetadatastorageviatagsandattributes,asseeninpom.xmlandweb.config.2.ItsupportsformalvalidationthroughXSDandDTDsche

How to manage dependencies with a pom.xml in Maven How to manage dependencies with a pom.xml in Maven Jan 03, 2026 am 01:42 AM

The pom.xml file declares dependencies through groupId, artifactId and version, and can use scope to specify the scope; 2. Multi-module projects use dependencyManagement to unify versions; 3. Maven automatically handles transitive dependencies, and exclusions can be used to exclude conflicting libraries; 4. Use MavenVersionsPlugin to check dependency updates to keep projects safe and consistent.

Related articles