Romulo Sousa
Romulo Sousa

Reputation: 243

How to read yaml files in laravel?

In the project I'm working on, it's a CMS, and within it I manage brand website themes. My question is I need to read the header of the file, how do I do this inside the controller?

I need somehow to read this file and list the titles of headers or footers that exist in it.

I'm using this package: https://github.com/antonioribeiro/yaml

menu.yaml

Upvotes: 11

Views: 11110

Answers (1)

syntaqx
syntaqx

Reputation: 2876

There's a great article about YAML here.

To excerpt from the page, you only need to follow a few simple steps:

1 Install the Symfony YAML Component using composer:

composer require symfony/yaml

2 In config/app.php under aliases, add the following entry:

'Yaml' => 'Symfony\Component\Yaml\Yaml'

3 In your desired controller/service:

use Yaml;
$yamlContents = Yaml::parse(file_get_contents('filepath'));

And that's it.

This solution works fairly universally, relying on PHP's composer library for you to include the library, then simply calling parse methods to unmarshal your YAML into a usable PHP variable. For the example shown here, try something like:

print_r($yamlContents)

To see how to use the data now that it's been converted.

Upvotes: 27

Related Questions