Maikuolan / Common

Common Classes Package.
GNU General Public License v2.0
7 stars 3 forks source link

How to write to YAML file? #11

Closed JeffHD closed 3 years ago

JeffHD commented 3 years ago

How do i edit a YAML file?

I have tried: $Object->Data['foo'] = 'bar';

but it dont work for me.

Maikuolan commented 3 years ago

Hi @JeffHD,

You can reconstruct the object's internal data array back into raw YAML data by using the reconstruct method. :-)

Documentation: Can the reverse be done, too? Can an array be converted into YAML data?

As a complete example, let's say if we have a YAML file, containing this:

String foo: "Bar"
Integer foo: 1234
Float foo: 123.4
Example numeric array:
 - "Bar1"
 - "Bar2"
 - "Bar3"
 - "Bar4"

If we wanted to change Integer foo from 1234 to 5678:

$OldData = file_get_contents('example.yaml');
$Object = new \Maikuolan\Common\YAML($OldData);
$Object->Data['Integer foo'] = 5678;
$NewData = $Object->reconstruct($Object->Data);
file_put_contents('example.yaml', $NewData);
JeffHD commented 3 years ago

Thanks that worked. Didn't fully understand the part at first because php is still quite new to me. Thank you