My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

What is the best way to update a YAML file in PHP?

Guy Castell's photo
Guy Castell
·Feb 27, 2017

Currently I'm using the Symfony YAML component, and my code is as follows (note that $blueprint is the data from the YAML file). It works, but I'm not sure of its elegance.

function update\\_blueprint($path, $data = []) {
// Get existing data
$blueprint = get\\\_blueprint($path);

// loop over the data and overwrite or create data
foreach($data as $key => $val) {

    $blueprint->$key = $val;

}

$blueprint = (array) $blueprint;
$yaml = \Symfony\Component\Yaml\Yaml::dump($blueprint);
$data = '---' . "\n";
$data .= $yaml;
$data .= '---';
$file = EMILIA\\\_DIR . '/\\\_site/blueprints/' . $path . '.yml';

file\\\_put\\\_contents($file, $data);

return true;
}