开发者

Convert YAML file to PHP File

I have a bunch of Yaml configuration files that I want to convert to straight PHP files so that the application does not have to process the Yaml files every time.

I know that there are a lot of libraries out there that will let you convert Yaml to a php array, but are there any libraries that will let you convert a yaml file to a php file?

The thing that makes this tricky is that converting a yaml file to php will usually produce a multi开发者_如何学Cdimensional array.

Thanks.

UPDATE:

I just realized that the following code does what I think i need. Notice the second paramter in the print_r. Pretty cool...

$test = print_r($yaml, true);
file_put_contents('test.php', $test);


There is a simple builtin to export a PHP variable/array, which allows you to write a small script for that task:

$array = yaml_import(...);

$array = var_export($array, 1);
file_put_contens($fn, "<?php \$array = $array; ?>");


Just Try Using the Symfony YAML Component

The Symfony2 Yaml component is very simple and consists of two main classes: one parses YAML strings (Parser), and the other dumps a PHP array to a YAML string (Dumper).

On top of these two classes, the Yaml class acts as a thin wrapper that simplifies common uses.

Reading YAML Files

The parse() method parses a YAML string and converts it to a PHP array:

use Symfony\Component\Yaml\Parser;

$yaml = new Parser();

$value = $yaml->parse(file_get_contents('/path/to/file.yml'));


file_put_contents('file.php', '<?php ' . var_export(your_yaml_parser_function_which_returns_php_array('file.yaml'), true));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜