+
80
-

php如何解析yaml文件?

php

php如何解析yaml文件?

网友回复

+
0
-

1、使用pecl的yaml扩展,https://pecl.php.net/package/yaml ,需要编译安装,性能好。

数组转yaml

<?php
$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"=> "Basketball",
            "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.",
  );
var_dump(yaml_emit($invoice));
?>

解析yaml文件成数组

<?php
$yaml = <<<EOD
---
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
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);
?>

2、使用composer包symfony/yaml,安装只需要 composer require symfony/yaml。

yaml转数组

<?php
require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
 
try {
    $value = Yaml::parseFile('./file.yaml');
} catch (ParseException $e) {
    echo $e->getMessage(); //
}
 
echo "<pre>";

数组 转yaml

<?php
require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Yaml\Yaml;
 
$arr = [
    'database' => [
        'host'   => '127.0.0.1',
        'user'   => 'root',
        'dbname' => 'test',
        'pwd'    => '123456',
    ],
];
 
$yaml = Yaml::dump($arr);
 
file_put_contents('./db.yaml', $yaml);

我知道答案,我要回答