Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify yaml file with PHP script

Tags:

php

yaml

symfony

I have a common.yml file with the following data :

main:
  shred:
    viral:
      image1:
        alt: Sunset
        src: 'http://i.imgur.com/nOptw.jpg'
      image2:
        alt: Fernie
        src: 'http://i.imgur.com/yfJaUoX.gif'

I am trying to make a php script which edits the 'src' attribute to new image i get from a new json file which i download. The problem is how do i edit the src of these 2 images. I tried to use Symfony Yaml component Dumper but dont know how to use it to update a particular part of my file.

Please help.....

like image 472
maths Avatar asked Dec 15 '22 22:12

maths


1 Answers

As you said you have to use the Symfony Yaml component.

For example you can access the "src" data :

$yaml = Yaml::parse(file_get_contents($this->container->get('kernel')->getRootDir() .'/config/common.yml'));

$srcData = $yaml['main']['schred']['viral']['image1']['src'];

Here, your data is accessible = 'http://i.imgur.com/nOptw.jpg'. Next you can change value and update your file :

$yaml['main']['schred']['viral']['image1']['src'] = $yourNewValue;

$new_yaml = Yaml::dump($yaml, 5);

file_put_contents($this->container->get('kernel')->getRootDir() .'/config/common.yml', $new_yaml);

Hope this can help you

like image 198
Perroin Thibault Avatar answered Dec 17 '22 11:12

Perroin Thibault