在 PHP 8.3 中,我正在使用 yaml_parse_file() 读取一个文件,如下所示:
summary: "Apples
Apples are a delicious fruit, unless they have worms in them."
当我
json_encode()
使用 parse_yaml_file()
生成的数组然后将其输出到文件时,输出如下所示:
Apples
Apples are a delicious fruit, unless they have worms in them."
所以看起来
yaml_parse_file()
正在修剪空白,并且它正在删除 Apples
和 Apples are a delicious fruit.
之间的空白行
但是,我需要保留该空行。 有没有简单的方法来保留它,或者我必须在
yaml_parse_file()
删除它之后将其添加回来?
这不是 PHP 解析器中的错误,这是定义为 YAML 规范的一部分:
在多行双引号标量中,换行符会受到流线折叠的影响,这会丢弃任何尾随空白字符。也可以转义换行符。在这种情况下,转义换行符将从内容中排除,并保留转义换行符之前的任何尾随空白字符。结合转义空白字符的能力,这允许在任意位置断开双引号行。
它正在删除
和Apples
之间的空行Apples are a delicious fruit.
请注意,这是被保留的完全空白行,第一行末尾的换行符是被剪切的内容。
为了避免这种情况,您可以使用转义序列对 YAML 进行编码:
summary: "Apples\n\nApples are a delicious fruit, unless they have worms in them."
或者也许只包含一个额外的显式空白来弥补被删除的空白:
summary: "Apples
Apples are a delicious fruit, unless they have worms in them."
您还可以使用特殊的管道
|
字符来指示块文字(但随后您必须考虑缩进):
summary: |
Apples
Apples are a delicious fruit, unless they have worms in them.