PHP - Install YAML Support

If you need to generate YAML files from PHP (perhaps for Docker Compose), then it is probably easiest to install the YAML Data Serialization PECL package. This tutorial will show you how to do that on Ubuntu.

Ubuntu 16.04 With PHP 7.0

sudo apt-get install php7.0-dev php-pear libyaml-dev -y
sudo pecl install yaml-2.0.0 -y

Update the php.ini file for the cli

SEARCH=";   extension=msql.so"
REPLACE=";   extension=msql.so\nextension=yaml.so"
FILEPATH="/etc/php/7.0/cli/php.ini"
sudo sed -i "s?$SEARCH?$REPLACE?" $FILEPATH

This will configured your PHP CLI to work with YAML. If you need to add apache support then also execute the following:

# Update the php.ini file for apache
SEARCH=";   extension=msql.so"
REPLACE=";   extension=msql.so\nextension=yaml.so"
FILEPATH="/etc/php/7.0/apache2/php.ini"
sudo sed -i "s?$SEARCH?$REPLACE?" $FILEPATH

Ubuntu 14.04 With PHP 5

Run the following bash script:

sudo apt-get install php5-dev php-pear libyaml-dev -y
sudo pecl install yaml

# Update the php.ini file for the cli
SEARCH=";   extension=msql.so"
REPLACE=";   extension=msql.so\nextension=yaml.so"
FILEPATH="/etc/php5/cli/php.ini"
sudo sed -i "s?$SEARCH?$REPLACE?" $FILEPATH

This will configured your PHP CLI to work with YAML. If you need to add apache support then also execute the following:

# Update the php.ini file for apache
SEARCH=";   extension=msql.so"
REPLACE=";   extension=msql.so\nextension=yaml.so"
FILEPATH="/etc/php5/apache2/php.ini"
sudo sed -i "s?$SEARCH?$REPLACE?" $FILEPATH

Test

Now you should be able to execute the following PHP script from the CLI:

<?php
$customer = array(
    "id" => 123,
    "first_name" => "Programster",
    "last_name" => "Page"
);

$obj = array(
    "id"=> 34843,
    "date"=> "2001-01-23",
    "customer"=> $customer,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338."
);

// generate a YAML representation of the invoice
$yaml = yaml_emit($obj);

print "yaml version is: " . PHP_EOL . $yaml . PHP_EOL;

The output of which should be:

yaml version is: 
---
id: 34843
date: "2001-01-23"
customer:
  id: 123
  first_name: Programster
  last_name: Page
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...

You should also be able to convert a YAML string back into a PHP data type with:

$parsed = yaml_parse($yaml);

References

Author

Programster

Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus