PHP code example of tbela99 / yaml

1. Go to this page and download the library: Download tbela99/yaml library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tbela99 / yaml example snippets



use Symfony\Component\Yaml\Ast\Node;

$ast = new Node();

$data = $ast->parse($yaml);

var_dump(isset($ast['services.redis.image'])); // true

echo $ast['services.redis.image']; // redis:alpine

unset($ast['services']);

echo $ast;


$ast['service.db'] = [
  'image' => 'mariadb',
  'environment' => [
    'NODE' => true,
    'SIZE' => '2G'
  ]
];

$ast['service.db.image']->addComment('mariadb image?');
$ast['service.db.environment']->addComment('environment variables');
$ast['service.db.environment.NODE']->addComment('killer app');
$ast['service.db.environment.SIZE']->addComment('going big here ...');

echo $ast;


$ast['service.db.environment.NODE'] = false;
$ast['service.db.environment.NODE']->setComments(['killer bee']);
$ast['service.db.environment.SIZE'] = '4G';
$ast['service.db.environment.RANGE'] = '100m';

echo $ast;


// binary value
$ast['service.db.environment.BIN'] = hex2bin('abcf');
// multiline string
$ast['service.db.environment.secret'] = "correct horse
battery staple";


/**
 * @var array $data
 */

$data = $ast->getValue();


/**
 * @var array $data
 */

$ast['version'] = 3.7;
$ast['author'] = 'a random guy';
$ast['authors.list'] = ['John', 'Raymond', 'Michael'];


unset($ast['service.db']);
echo $ast;

use Symfony\Component\Yaml\Ast\Node;
use Symfony\Component\Yaml\Ast\Value;

$ast = new Node();

// parse Yaml string
$ast->parse($yaml);
//or parse Yaml file
$ast->parseFile($file);

// alter the ast
$ast['version'] = '1.0';
$ast['version']->addComment('this comment is associated to the version number');
// or
$ast->appendValue(1.0, 'version', ['this comment is associated to the version number']);
// or
$ast->appendNode(new Value(1.0), 'version', ['this comment is associated to the version number']);

// render the ast
$yaml = (string) $ast;

// do something useful with the output
file_put_contents('configuration.yaml', $yaml);


$ast = new Node();

$ast['path.to.data'] = "user name";

// use '.' in the key name
$ast[$ast->escapeKey('v0.1')] = [

  'description' => 'first stable release',
  'download' => 'https://example.com'
];

$ast['versions'] = [
  'v0.1' => [

    'description' => 'first stable release',
    'download' => 'https://example.com'
  ]
];

echo $ast;

$data = 
'path:
 to:
  name: "John Henry"
versions:
 v0.2:
  description: "second stable release"
  download: "https://example.com/2"';

$node = new Node();

$node->parse($data);

$ast->merge($node);

echo "$ast\n\n";