skip to Main Content

In PHP, when working with YAML, is it possible to work with a specific document inside of the yaml file?

Eg

--- #settings
Settings go here
...

--- #user
Users go here
...

Is it possible to load only users into php so I can work only with that documents data?

2

Answers


  1. use Symfony YAML Component or Spyc

    <?php
    require_once 'vendor/autoload.php'; // Load the autoload from Symfony YAML Component
    
    use SymfonyComponentYamlYaml;
    
    // YAML file path
    $file = 'path/to/your/file.yaml';
    
    // Load the entire YAML file
    $data = Yaml::parseFile($file);
    
    // Access the data for the 'user' section
    $usersData = $data['user'];
    
    // Now you can work with $usersData
    // ...
    ?>
    
    Login or Signup to reply.
  2. It is possible. As noted in some comments, some popular libraries do not support this (Symfony YAML does not). But if you have the php YAML extension, the document number is just an additional paramenter of yaml_parse. Pass pos 1 to load only the second document in your example.

    From the PHP documentation:

     yaml_parse(
        string $input,
        int $pos = 0,
        int &$ndocs = ?,
        array $callbacks = null ): mixed
    

    where:

    pos

    Document to extract from stream (-1 for all documents, 0 for first document, …).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search