Learn the use of YAML operation extensions in PHP

硬核项目经理
中文

To be honest, I don’t use YAML much. When learning about automated testing, I have been exposed to using this configuration file to configure the continuous integration operation of Travis CI. Of course, it was mainly learning at the time. Although there are not many contacts, I also know that the writing of this configuration format has basically become the mainstream now. Therefore, I won’t explain more about the specific YAML-related content here, and students who are not too familiar can consult some related documents on their own.

What we are learning today is mainly an extension used to parse and convert YAML format in PHP. There is nothing special about the installation process, just install it like other extensions. However, this extension requires a libyaml-devel, which cannot be installed directly through yum or dnf in CentOS. We can find the download address in the link at the end of the article.

Convert PHP data to YAML

For converting PHP data into YAML, it is actually similar to JSON-related operations, converting an array into a YAML format string.

$addr = array(
    "given" => "Chris",
    "family"=> "Dumars",
    "address"=> array(
        "lines"=> "458 Walkman Dr.
        Suite #292",
        "city"=> "Royal Oak",
        "state"=> "MI",
        "postal"=> 48046,
      ),
  );
$invoice = array (
    "invoice"=> 34843,
    "date"=> 980208000,
    "bill-to"=> $addr,
    "ship-to"=> $addr,
    "product"=> array(
        array(
            "sku"=> "BL394D",
            "quantity"=> 4,
            "description"=> "篮球",
            "price"=> 450,
          ),
        array(
            "sku"=> "BL4438H",
            "quantity"=> 1,
            "description"=> "Super Hoop",
            "price"=> 2392,
          ),
      ),
    "tax"=> 251.42,
    "total"=> 4443.52,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
  );

$yamlString = yaml_emit($invoice);
var_dump($yamlString);
// string(624) "---
// invoice: 34843
// date: 980208000
// bill-to:
//   given: Chris
//   family: Dumars
//   address:
//     lines: |-
//       458 Walkman Dr.
//               Suite #292
//     city: Royal Oak
//     state: MI
//     postal: 48046
// ship-to:
//   given: Chris
//   family: Dumars
//   address:
//     lines: |-
//       458 Walkman Dr.
//               Suite #292
//     city: Royal Oak
//     state: MI
//     postal: 48046
// product:
// - sku: BL394D
//   quantity: 4
//   description: "\u7BEE\u7403"
//   price: 450
// - sku: BL4438H
//   quantity: 1
//   description: Super Hoop
//   price: 2392
// tax: 251.42
// total: 4443.52
// comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
// ...
// "

You can see that the conversion result of the yaml_emit() function is a very standard YAML format. There is --- at the beginning and... at the end. But you will find that there are many tutorials or frameworks in the .yml file that do not have these symbols. According to the official documentation, these symbols are recommended to be written, and our extensions follow the recommendations very much, which is the result of the conversion. Very standard.

In addition, we added Chinese content to the test code. You can see that the Chinese is encoded during direct conversion. Just like JSON operations, in the extended function of YAML, we can also specify the encoding format to display Chinese as it is.

var_dump(yaml_emit($invoice, YAML_UTF8_ENCODING));
// string(616) "---
// ………………
//   description: 篮球
// ………………
// ...
// "

Convert YAML to PHP array

Yes, it is similar to the JSON operation, in which the string format content in the YAML format is reversed back to the PHP data content.

var_dump(yaml_parse($yamlString));
// array(8) {
//     ["invoice"]=>
//     int(34843)
//     ["date"]=>
//     int(980208000)
//     ["bill-to"]=>
//     array(3) {
//       ["given"]=>
//       string(5) "Chris"
//       ["family"]=>
//       string(6) "Dumars"
// ………………
// ………………

It is also very simple a yaml_parse() function. In addition to directly manipulating the string, we can also directly extract the contents of the file for conversion, including the above yaml_emit() function, which also writes the result directly into the file.

var_dump(yaml_parse_file('styleci.yml'));
// array(3) {
//     ["php"]=>
//     array(3) {
//       ["preset"]=>
//       string(7) "laravel"
//       ["disabled"]=>
//       array(1) {
//         [0]=>
//         string(10) "unused_use"
//       }
//       ["finder"]=>
//       array(1) {
//         ["not-name"]=>
//         array(2) {
//           [0]=>
//           string(9) "index.php"
//           [1]=>
//           string(10) "server.php"
//         }
//       }
//     }
//     ["js"]=>
//     array(1) {
//       ["finder"]=>
//       array(1) {
//         ["not-name"]=>
//         array(1) {
//           [0]=>
//           string(14) "webpack.mix.js"
//         }
//       }
//     }
//     ["css"]=>
//     bool(true)
//   }

The file we tested is the .styleci.yml file that comes with Laravel. In the Laravel framework, we are not required to install this YAML extension. It seems that the framework itself has tools to solve the problem of reading and converting the YAML format, which we will talk about last. Similar to yaml_parse_file(), yaml_emit_file() directly converts PHP data into YAML format and writes it directly into a file. You can test it yourself.

Callback function processing label

Both yaml_emit() or yaml_parse() support a callback parameter operation. Let's take a look at an example first.

// php:
//   preset: !laravel laravel
//   disabled:
// ………………
// ………………
function callback($value){
    return str_replace('laravel', 'new version laravel8', $value);
}
$ndocs = 0;
var_dump(yaml_parse_file('styleci.yml', 0, $ndocs, ['!laravel'=>'callback']));
// array(3) {
//     ["php"]=>
//     array(3) {
//       ["preset"]=>
//       string(20) "new version laravel8"
//       ["disabled"]=>
//       array(1) {
// ……………………
// ……………………

What does it mean? !laravel can be regarded as a label format in YAML. The function of this callback is to use what callback function to process when a similar type of label is encountered. For example, the content after !laravel in our original document is laravel. In the callback function, we replaced the content with the new version laravel8, so the final output result is that the content of the preset field becomes the new version laravel8. Of course, more detailed content and more syntax still require us to understand the syntax of the YAML format more clearly, so I won't say much here, after all, I don't have much contact with it.

Summarize

There is not much content for this extension, and even if it is necessary to operate the configuration file in YAML format in a real business environment, it is estimated that I will not use it. why? Of course, it is because there are already many components that handle YAML in Composer for us to use. There is no need to change the PHP environment on the server by means of extension compilation and installation. If you are using it yourself, you can find many components in packagist.org, and if you are using Laravel, its underlying use is actually the yaml processing component in the symfony framework. You can directly use composer require symfony/yaml to add this component to your own small project. The specific content can refer to this document:

https://symfony.com/doc/current/components/yaml.html

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/2021/01/source/10. Learn the use of YAML operation extensions in PHP. php

Reference documents:

https://www.php.net/manual/zh/book.yaml.php

http://www.rpmfind.net/linux/rpm2html/search.php?query=libyaml-devel(x86-64))

http://bd808.com/pecl-file_formats-yaml/

阅读 957
87 声望
16 粉丝
0 条评论
87 声望
16 粉丝
文章目录
宣传栏