Questions And Answers

More Tutorials


Installing YAML extension

YAML does not come with a standard PHP installation, instead it needs to be installed as a PECL extension. On linux/unix it can be installed with a simple
pecl install yaml

Note that libyaml-dev package must be installed on the system, as the PECL package is simply a wrapper around libYAML calls. Installation on Windows machines is different - you can either download a pre-compiled DLL or build from sources.

Using YAML to store application configuration

YAML provides a way to store structured data. The data can be a simple set of name-value pairs or a complex hierarchical data with values even being arrays.

Consider the following YAML file:
 driver: mysql
 port: 3306
 db_name: sample_db
 user: myuser
 password: Passw0rd
debug: true
country: us

Let's say, it's saved as config.yaml. Then to read this file in PHP the following code can be used:

$config = yaml_parse_file('config.yaml');
print_r will produce the following output:
 [database] => Array
 [driver] => mysql
 [host] =>
 [port] => 3306
 [db_name] => sample_db
 [user] => myuser
 [password] => Passw0rd
 [debug] => 1
 [country] => us

Now config parameters can be used by simply using array elements:

$dbConfig = $config['database'];
$connectString = $dbConfig['driver']
 . ":host={$dbConfig['host']}"
 . ":port={$dbConfig['port']}"
 . ":dbname={$dbConfig['db_name']}"
 . ":user={$dbConfig['user']}"
 . ":password={$dbConfig['password']}";
$dbConnection = new \PDO($connectString, $dbConfig['user'], $dbConfig['password']);


In this page (written and validated by ) you learned about PHP YAML . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP SOAP Server.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.