简体   繁体   English

将YAML文件转换为PHP文件

[英]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. 我有一堆Yaml配置文件,我想转换为直接的PHP文件,以便应用程序不必每次都处理Yaml文件。

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? 我知道有很多库可以让你将Yaml转换为php数组,但有没有任何库可以让你将yaml文件转换成php文件?

The thing that makes this tricky is that converting a yaml file to php will usually produce a multidimensional array. 使这个棘手的事情是将yaml文件转换为php通常会产生一个多维数组。

Thanks. 谢谢。

UPDATE: 更新:

I just realized that the following code does what I think i need. 我刚刚意识到以下代码可以完成我认为我需要的代码。 Notice the second paramter in the print_r. 注意print_r中的第二个参数。 Pretty cool... 很酷......

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

Just Try Using the Symfony YAML Component 只需尝试使用Symfony YAML组件

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). Symfony2 Yaml组件非常简单,由两个主要类组成:一个解析YAML字符串(Parser),另一个将PHP数组转储到YAML字符串(Dumper)。

On top of these two classes, the Yaml class acts as a thin wrapper that simplifies common uses. 在这两个类之上,Yaml类充当一个简化包装器,简化了常见用途。

Reading YAML Files 阅读YAML文件

The parse() method parses a YAML string and converts it to a PHP array: parse()方法解析YAML字符串并将其转换为PHP数组:

use Symfony\Component\Yaml\Parser;

$yaml = new Parser();

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

There is a simple builtin to export a PHP variable/array , which allows you to write a small script for that task: 有一个简单的内置导出PHP变量/数组 ,允许您为该任务编写一个小脚本:

$array = yaml_import(...);

$array = var_export($array, 1);
file_put_contens($fn, "<?php \$array = $array; ?>");
file_put_contents('file.php', '<?php ' . var_export(your_yaml_parser_function_which_returns_php_array('file.yaml'), true));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM