PHPプログラムに関する各種メモ書き

PHPで(symfony/yaml)を使ってYAMLをパースする

PHPでは hjson(コメント付きjson) がいまいち使えない( laktak/hjson ではマルチバイトでエラーが出るみたい。。。)なので、
設定ファイルにコメントを入れたい時はYAMLを使用します。

● symfony/yaml

https://packagist.org/packages/symfony/yaml

インストール

composer require symfony/yaml

使い方

<?php
require __DIR__ . '/vendor/autoload.php';
$input = '{foo: "bar"}';
$result = \Symfony\Component\Yaml\Yaml::parse($input);
var_dump($result);

パースすると配列になります。

配列をオブジェクトに変換する

$result = json_decode(json_encode($result));

PHPの配列を yaml フォーマットにする

$yaml = \Symfony\Component\Yaml\Yaml::dump($array,99);

引数は以下の通り。

    /**
     * Dumps a PHP value to a YAML string.
     *
     * The dump method, when supplied with an array, will do its best
     * to convert the array into friendly YAML.
     *
     * @param mixed $input  The PHP value
     * @param int   $inline The level where you switch to inline YAML
     * @param int   $indent The amount of spaces to use for indentation of nested nodes
     * @param int   $flags  A bit field of DUMP_* constants to customize the dumped YAML string
     *
     * @return string A YAML string representing the original PHP value
     */
    public static function dump($input, int $inline = 2, int $indent = 4, int $flags = 0): string
    {
        $yaml = new Dumper($indent);
        return $yaml->dump($input, $inline, 0, $flags);

● YAMLのヒアドキュメント

( 半角スペース1つ と | )

view_data: |
    1行目です。
    2行目です。
    3行目です。
No.1430
06/11 09:37

edit