Windows.  Viruses.  Notebooks.  Internet.  office.  Utilities.  Drivers

(PECL yaml >= 0.4.0)

yaml_parse- Parses a YAML stream

Description

yaml_parse (string $input [, int $pos = 0 [, int &$ndocs [, array $callbacks = NULL ]]]) : mixed

Converts all or part of the YAML stream and writes to a variable.

Parameter List

Line for parsing as a YAML stream.

parsing document ( -1 for all documents 0 for the first document, ...).

If ndocs is found, then it will be replaced by the number of documents in the YAML stream.

Return Values

Returns the value encoded in input in the corresponding PHP type, or FALSE in case of an error. If pos parameter equals -1 , an array will be returned containing one entry for each document found in the stream.

Examples

Example #1 Usage example yaml_parse()

$yaml =<<---
invoice: 34843
date: "2001-01-23"
bill-to: &id001
given: Chris
family: Dumars
address:
lines: |-
458 Walkman Dr.
Suite #292
city: Royal Oak
state: MI
postal: 48046
site: zxibit.esy.es
ship-to: *id001
product:
-SKU: BL394D
quantity: 4
Description: Basketball
price: 450
- sku: BL4438H
quantity: 1
description: Super Hoop
price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
EOD;

$parsed = yaml_parse($yaml);
var_dump($parsed);
?>

The result of running this example will be something like this:

array(8) ( ["invoice"]=> int(34843) ["date"]=> string(10) "2001-01-23" ["bill-to"]=> &array(3) ( [" given"]=> string(5) "Chris" ["family"]=> string(6) "Dumars" ["address"]=> array(4) ( ["lines"]=> string(34) " 458 Walkman Dr. Suite #292" ["city"]=> string(9) "Royal Oak" ["state"]=> string(2) "MI" ["postal"]=> int(48046) ) ) ["ship-to"]=> &array(3) ( ["given"]=> string(5) "Chris" ["family"]=> string(6) "Dumars" ["address"]=> array (4) ( ["lines"]=> string(34) "458 Walkman Dr. Suite #292" ["city"]=> string(9) "Royal Oak" ["state"]=> string(2) "MI" ["postal"]=> int(48046) ) ) ["product"]=> array(2) ( => array(4) ( ["sku"]=> string(6) "BL394D" [ "quantity"]=> int(4) ["description"]=> string(10) "Basketball" ["price"]=> int(450) ) => array(4) ( ["sku"]=> string(7) "BL4438H" ["quantity"]=> int(1) ["description"]=> string(10) "Super Hoop" ["price"]=> int(2392) ) ) ["tax" ]=> float(251.42) ["total"]=> float(4443.52) ["comments"]=> string(68) "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338." )

The day has come and configuration files for our application have become so large that the managers hinted that there are suspiciously many curly and non-curly braces in JSON configs, and they would like to get rid of them. A subtle hint was given that it would be nice to take a closer look at YAML, because there are rumors that it is very human-readable. And there are no brackets. And the lists are beautiful. Naturally, we could not help listening to the elders, we had to study the issue, look for the difference, the pros and cons of both formats. Obviously, such comparisons are made only to confirm the opinion of the leaders, or even if not confirmed, they will find why they are right and why it is worth making changes :)

I am sure that many are familiar with these formats, but still I will give short description from wikipedia:

JSON (JavaScript Object Notation) is a text-based data exchange format based on JavaScript and commonly used with this language. Like many other text formats, JSON is easy for humans to read. Despite its origins in JavaScript (more precisely, a subset of the language of the 1999 ECMA-262 standard), the format is considered language independent and can be used with almost any programming language. For many languages, there is ready-made code for creating and processing data in JSON format.

YAML is a human-readable data serialization format, conceptually close to markup languages, but focused on the convenience of input/output of typical data structures of many programming languages. The name YAML is a recursive acronym for YAML Ain "t Markup Language ("YAML is not a markup language"). The name reflects the history of development: in the early stages, the language was called Yet Another Markup Language ("Another markup language") and was even considered as a competitor XML, but was later renamed to emphasize data rather than document markup.

And so what we need:

  • make the same complex JSON and YAML
  • determine the parameters by which we will compare
  • deserialize in Java objects about 30 times
  • compare speed results
  • compare file readability
  • compare usability with format

Obviously, we are not going to write our own parsers, so to begin with, we will choose an already existing parser for each format.
For json, we will use gson (from google), and for yaml - snakeyaml (from don't-know-who).

As you can see, everything is simple, you just need to create a fairly complex model that will simulate the complexity of config files, and write a module that will test yaml and json parsers. Let's get started.
We need a model of approximately this complexity: 20 attributes different types+ 5 collections of 5-10 elements + 5 nested objects of 5-10 elements and 5 collections.
This stage of the whole comparison can be safely called the most tedious and uninteresting. Classes were created, with unsounding names like Model, Emdedded1, and so on. But we are not chasing the readability of the code (at least in this part), so we will leave it like that.

file.json

"embedded2": ( "strel1": "el1", "strel2": "el2", "strel4": "el4", "strel5": "el5", "strel6": "el6", "strel7": " el7", "intel1": 1, "intel2": 2, "intel3": 3, "list1": [ 1, 2, 3, 4, 5 ], "list2": [ 1, 2, 3, 4, 5, 6, 7 ], "list3": [ "1", "2", "3", "4" ], "list4": [ "1", "2", "3", "4", "5", "6" ], "map1": ( "3": 3, "2": 2, "1": 1 ), "map2": ( "1": "1", "2": "2", "3": "3" ) )


file.yml

embedded2: intel1: 1 intel2: 2 intel3: 3 list1: - 1 - 2 - 3 - 4 - 5 list2: - 1 - 2 - 3 - 4 - 5 - 6 - 7 list3: - "1" - "2" - "3" - "4" list4: - "1" - "2" - "3" - "4" - "5" - "6" map1: "3": 3 "2": 2 "1": 1 map2: 1: "1" 2: "2" 3: "3" strel1: el1 strel2: el2 strel4: el4 strel5: el5 strel6: el6 strel7: el7


I agree that human readability is a rather subjective parameter. But still, in my opinion, yaml is a little more pleasing to the eye and more intuitive.

yaml parser

public class BookYAMLParser implements Parser ( String filename; public BookYAMLParser(String filename) ( this.filename = filename; ) @Override public void serialize(Book book) ( try ( DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(options); FileWriter writer = new FileWriter(filename); yaml.dump(book, writer); writer.close(); ) catch (IOException e) ( e.printStackTrace(); ) ) @Override public Book deserialize() ( try ( InputStream input = new FileInputStream(new File(filename)); Yaml yaml = new Yaml(); Book data = (Book) yaml.load(input); input.close(); return data; ) catch (FileNotFoundException e) ( e.printStackTrace(); ) catch (YamlException e) ( e.printStackTrace(); ) catch (IOException e) ( e.printStackTrace(); ) catch (Exception e) ( String message = " Exception in file " + filename + ", "; throw new Exception(message + e.getMessage()); ) return null; ) )

json parser

public class BookJSONParser implements Parser ( String filename; public BookJSONParser(String filename) ( this.filename = filename; ) @Override public void serialize(Book book) ( Gson gson = new GsonBuilder().setPrettyPrinting().create();; try ( FileWriter writer = new FileWriter(filename); String json = gson.toJson(book); writer.write(json); writer.close(); ) catch (IOException e) ( e.printStackTrace(); ) ) @Override public Book deserialize( ) ( Gson gson = new Gson(); try ( BufferedReader br = new BufferedReader(new FileReader(filename)); JsonReader jsonReader = new JsonReader(br); Book book = gson.fromJson(jsonReader, Book.class); return book ; ) catch (IOException e) ( e.printStackTrace(); ) return null; ) )

As we can see both formats are supported in java. But for json, the choice is much wider, that's for sure.
The parsers are ready, now let's look at the implementation of the comparison. Here, too, everything is extremely simple and obvious. There is a simple method that deserializes objects from a file 30 times. If anyone is interested - the code is under the spoiler.

testing code

public static void main(String args) ( String jsonFilename = "file.json"; String yamlFilename = "file.yml"; BookJSONParser jsonParser = new BookJSONParser(jsonFilename); jsonParser.serialize(new Book(new Author("name", "123-123-123"), 123, "dfsas")); BookYAMLParser yamlParser = new BookYAMLParser(yamlFilename); yamlParser.serialize(new Book(new Author("name", "123-123-123")), 123 , "dfsas")); //json deserialization StopWatch stopWatch = new StopWatch(); stopWatch.start(); for (int i = 0; i< LOOPS; i++) { Book e = jsonParser.deserialize(); } stopWatch.stop(); System.out.println("json worked: " + stopWatch.getTime()); stopWatch.reset(); //yaml deserialization stopWatch.start(); for (int i = 0; i < LOOPS; i++) { Book e; e = yamlParser.deserialize(); } stopWatch.stop(); System.out.println("yaml worked: " + stopWatch.getTime()); }

As a result, we get the following result:
json worked: 278 yaml worked: 669

As you can see, json files are parsed about three times faster. But the absolute difference is not critical, on our scale. Therefore, this is not a strong plus in favor of json.
This happens because json is parsed on the fly, that is, it is read character by character and immediately stored in an object. It turns out the object is formed in one pass through the file. Actually, I don't know how exactly this parser works, but in general scheme such.
And yaml, in turn, is more measured. The data processing stage is divided into 3 stages. First, a tree of objects is built. Then it is still somehow transformed. And only after this stage it is converted into the necessary data structures.

small comparison table("+" - advantage, "-" - lag, "+-" - no clear advantage):

How can this be summed up?
Everything is obvious here, if speed is important to you - then json, if human readability - yaml. You just need to decide what is more important. For us it turned out - the second.
In fact, there are many more different arguments in favor of each of the formats, but I think that these two points are the most important.

Further, when working with yaml, I had to deal with not very beautiful exception handling, especially with syntax errors. Also, I had to test various yaml libraries. Also, in the end, it was necessary to write some kind of validation. We tried schema validation (where we had to call ruby ​​gems), and bean validation based on jsr-303. If you are interested in any of these topics - I will be happy to answer questions.
Thank you for your attention:)

P.S.
Already at the end of writing the article, I came across the following comparison of yaml and json.

1. In the list of products, click "Upload"

After uploading the goods to the parser, being on the page with the list of goods, click the "Upload" button.

2. Set the format settings

In the window that appears, select the "Yandex.Market (YML)" format and set the format settings: how to upload characteristics and separate properties.

A detailed description of each setting can be found below on this page.

3. Upload started

The unloading goods indicator will appear. If you don't want to wait, you can turn off your computer or close your browser - the download will continue regardless of you.

What is YML?

YML (Yandex Market Language) is a standard developed by Yandex for accepting and placing information in the Yandex.Market database. YML is based on the XML standard.

Format settings:

Generate offer id from— allows you to select the method of generating the id attribute for the offer tag, which defines the product offer ID.

Share multiproperties— allows you to choose how to separate the selected properties (Sizes, Colors, etc.): either based on the repeated param tag, or based on splitting the offer into individual products by group_id, according to the YML specification.

Items out of stock- you can set how the "Out of stock" products will be displayed in the market: On order, i.e. with the ability to order or completely out of stock.

General settings:

Unload goods— allows you to select which products to unload based on the "Availability" attribute on the supplier's website.

The procedure for unloading goods- allows you to select the order of unloading goods and set unloading backwards if desired.

Allow HTML markup in product fields— allows or disables HTML markup in product fields. Very rarely used by online stores.

Uploading images- allows you to change the number or method of uploading images.

Unloading characteristics- allows you to upload product properties (colors, sizes, etc.) as separate fields in a file or simply add to general description goods. When added to the description, the columns themselves remain. It is selected depending on the capabilities of your online store or JV website.

Split into multiple files— allows you to split the upload into several files: by category or by brand.

Found an error in uploading to this format?

If you find an error in the Yandex.Market (YML) upload format, please let us know on or in the chat on the site. We will try to fix the upload as soon as possible.

The plugin allows you to import products from other stores via Yandex XML feed, which is used by stores for trading on Yandex.Market.
Products are imported into the WP Shop plugin structure. There is automatic synchronization of goods with the source, which can be launched both manually and through cron.
An indispensable tool for:
1. Transferring the store from any other engines to WordPress WP-Shop
2. Building affiliate stores to earn on affiliate commissions using the CPS model

The application requires IonCube Loader!

Arbitrary section 1

FAQ

Installation Instructions
  1. Upload plugin "WP Shop YML Parser" to the /wp-content/plugins/ directory
  2. Activate the plugin "WP Shop YML Parser" through the ‘Plugins’ menu in WordPress
  3. See full userguide how to set up your "WP Shop YML Parser"
A question that someone might have

Visit the site wp-shop.ru for help.

Reviews

In no case do not contact these developers and do not buy anything from them. The functionality that they promise in the pro version is a hoax. They will simply take money from you, and then they will refuse everything, including support. Just look at their crooked website and semi-live documentation and you will understand everything!

Changelog

Version: 0.9
-project_as_field
-id_as_field

Version: 0.8
-template_price (custom price tag)

Version: 0.7
-fields_update - new setting to update custom fields in projects

Version: 0.6
-Sample xml parser replaced by SAX parser that better for memory management

Version: 0.5
-improvements

Version: 0.4
-bulk analizing
-clone project by category

Version: 0.3
-link to docs

Version: 0.2
-local feeds enable
- source as file enable
- addition yml options

Version: 0.1
-initial release

Instrument testing, configuration files, and log files should all be human-readable. YAML (YAML Non Markup Language) has less verbose data than the XML serialization format and has become a popular format among developers software mainly because it is easier for human understanding. YAML files are easy text files, which contains data written according to the YAML syntax rule and usually has a .yml file extension. In this article, you will learn the basics of YAML and how you can integrate a PHP YAML parser into your projects.

Use YAML for PHP projects

Understanding YAML Syntax

YAML supports advanced features such as references and custom data types, but as a PHP developer, most of the time you will be interested in how YAML represents enumerated arrays (sequences in YAML terminology) and associative arrays (maps).

This is how an enum is represented in a YAML array:

- "William O'Neal" - false

Each array element is represented after a hyphen and a space. Its syntax for representing values ​​is similar to PHP (quoting strings, etc.)

Above is equivalent to the following PHP:

Typically, each element appears on its own line in YAML, but listed arrays can be expressed on one line using parentheses:

[ 2, "William O'Neil", false ]

The following code shows what an associative array is in YAML:

Id: 2 name: "William O'Neal" isActive: false

The first element key specifies a colon and one or more spaces, and then the value is specified. Having just one space after the colon is enough, but you can use more space for better readability if you like.

The PHP equivalent of the above YAML array is:

2, "name" => "William O'Neil", "isActive" => false);?>

And similar to enumerated arrays, you can express associative arrays on one line using curly braces:

( id: 2, name: "William O"Neil", isActive: false )

With one or more spaces to indent, you can represent a multidimensional array like this:

Above the YAML block, this is equivalent to the following PHP:

array(0 => array("id" => 1, "name" => "Brad Taylor", "isActive" => true), 1 => array("id" => 2, "name" => " William O"Neal", "isActive" => false)));?>

YAML also allows you to represent a collection of data elements in a single document without requiring a root node. The following example contains the content of article.yml , which shows multiple multidimensional arrays in a single file.

Author: 0: ( id: 1, name: "Brad Taylor", isActive: true ) 1: ( id: 2, name: "William O"Neal", isActive: false ) category: 0: ( id: 1, name : "PHP" ) 1: ( id: 2, name: "YAML" ) 2: ( id: 3, name: "XML" ) article: 0: id: 1 title: "How to Use YAML in a PHP Project" content: >YAML is a less verbose data serialization format.Behind it stands "YAML is not a Markup Language".YAML has been a popular data serialization format among software developers, mainly because it is human readable.author: 1 status: 2 articleCategory: 0 : ( articleId: 1, categoryId: 1 ) 1: ( articleId: 1, categoryId: 2 )

While most of the YAML syntax is intuitive and easy to remember, there is one important rule to keep in mind. Alignment must be done with one or more spaces; tabs are not allowed. You can set the IDE to insert spaces instead of tabs when you press the tab key, which is a common configuration among software developers to make sure code is correctly indented and displayed when viewed in other editors.

You can learn more advanced features and syntax, and what YAML supports by reading the official docs, Symfony or the Wiki.

YAML should not be an alternative to XML

If you are researching YAML with your loved one search engine, you are definitely on the topic "YAML vs. XML", and naturally, when you first see YAML, you will generally prefer it over XML because it is easier to read and write. However, YAML should still be one tool in a developer's arsenal and should not be an alternative to XML Here are some of the benefits of YAML and XML.

Benefits of YAML

  • Less verbose, easy to compose and more readable
  • Does not have a tree structure with a single parent node

Benefits of XML

  • More built-in PHP support compared to YAML
  • XML has become the de facto standard for communication between communication applications
  • XML tags can have attributes providing more details about private data

Although verbose, XML is more readable and maintainable when the element hierarchy is deep compared to YAML's space-oriented representation of the hierarchy.

Considering the advantages in both languages, YAML seems to be more suitable for collection of different datasets and when people are also one of the consumer data.

Choice Parser PHP YAML

YAML parser, has two functionality, a kind of load for a function that converts YAML to an array, and a dump of a function that converts an array to YAML.

The current PHP YAML parser is available as a PECL extension and is not bundled with PHP. In addition, there are parsers written in pure PHP that would be slightly slower compared to the PECL extension.

Below are a few YAML parsers for PHP:

  • Not shipped with PHP
  • You will need root access to the server to install
  • Implemented in PHP
  • Will work in PHP 5.2.4+
  • Need to extract frameworks from Symfony
  • Implemented in PHP
  • Will work in PHP 5.3.2+
  • Implemented in PHP
  • Will work in PHP 5+

I prefer to choose Symfony 1.4 YAML components due to portability (it works with PHP 5.2.4+) and redemption (Symfony 1.4 and PHP frameworks installed). Once you have extracted the YAML archive of the Symfony components, the YAML classes are available under lib/yaml . The static load() and dump() methods are available from the sfYaml class.

Integration into Parser PHP YAML project

Whenever you integrate a third party class or library into your PHP project, it's a good practice to create wrapper and tests. Changing a third-party library with minimal changes to the project code (only the shell should be related to the project code) and with the confidence that the changes will not slow down any functionality (tests).

The following test (YamlParserTest.php) has been created for its wrapper class (YamlParser.php). Required to run and maintain the test. You can add more tests if you want, for invalid filenames and file extensions other than .yml , and other script-based tests you will encounter in your project.

yamlParser = new YamlParser(); ) public function testMainArrayKeys() ( $parsedYaml = $this->yamlParser->load("article.yml"); $mainArrayKeys = array_keys($parsedYaml); $expectedKeys = array("author", "category", "article ", "articleCategory"); $this->assertEquals($expectedKeys, $mainArrayKeys); ) public function testSecondLevelElement() ( $parsedYaml = $this->yamlParser->load("article.yml"); $actualArticle = $ parsedYaml["article"]; $title = "How to Use YAML in Your Next PHP Project"; $content = "YAML is a less-verbose data serialization format. " . "It stands for \"YAML Ain"t Markup Language\". " . "YAML has been a popular data serialization format among " . "software developers mainly because it"s human-readable.\n"; $expectedArticle = array("id" => 1, "title" => $title, "content" => $content, "author" => 1, "status" => 2); $this->assertEquals($expectedArticle, $actualArticle); } /** * @expectedException YamlParserException */ public function testExceptionForWrongSyntax() { $this->yamlParser->load("wrong-syntax.yml"); } }?> !}

And here is the wrapper class:

getMessage(), $e->getCode(), $e); ) ) public function dump($array) ( try ( return sfYaml::dump($array); ) catch (Exception $e) ( throw new YamlParserException($e->getMessage(), $e->getCode(), $e); ) ) ) class YamlParserException extends Exception ( public function __construct($message = "", $code = 0, $previous = NULL) ( if (version_compare(PHP_VERSION, "5.3.0")< 0) { parent::__construct($message, $code); } else { parent::__construct($message, $code, $previous); } } }?>

P.S.

So now you have the knowledge of what YAML is and how to represent PHP arrays to YAML, and integrate the PHP YAML parser into your projects. By spending a little time with the YAML syntax, you will be able to understand the potential of the possibilities it provides. You may also want to consider looking into Symfony 1.4 and 2 which makes extensive use of YAML.

If you notice an error, select a piece of text and press Ctrl + Enter
SHARE: