php 通过 fwrite 向输出文件添加换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6683595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding line breaks to output file via fwrite
提问by Scott B
I'm trying to format the file I'm creating below so that each name/value pair is on its own line
我正在尝试格式化我在下面创建的文件,以便每个名称/值对都在自己的行上
I'm sure this is easy, but my .ini file is not formatting the line breaks at all. what am I missing?
我确信这很容易,但我的 .ini 文件根本没有格式化换行符。我错过了什么?
function wpseTest()
{
$query = "SELECT option_name, option_value FROM wp_options where option_name like 'test|_%' escape '|' AND option_value > ''";
global $wpdb;
$matches = $wpdb->get_results($query);
$mySettings = '[settings]\r\n';
foreach ($matches as $result){
$mySettings .= $result->option_name;
$mySettings .= ' = ';
$mySettings .= $result->option_value;
$mySettings .= '\r\n';
}
$mySettingsFileLocation = WP_PLUGIN_DIR.'/test/settings-backup.ini';
$mySettingsFile = fopen($mySettingsFileLocation, 'w');
fwrite($mySettingsFile, $mySettings);
fclose($mySettingsFile);
}
回答by user703016
Special characters like \r
and \n
do not get interpreted in single quotes. Use double quotes instead.
特殊字符如\r
和\n
不会被解释为单引号。请改用双引号。
$mySettings = "[settings]\r\n";
And
和
$mySettings .= "\r\n";
回答by KingCrunch
You can use the platform dependent constant PHP_EOL
instead
您可以使用该平台相关的常数PHP_EOL
代替
$mySettings = '[settings]' . PHP_EOL;
// ..
$mySettings .= PHP_EOL;
回答by genesis
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
function wpseTest()
{
$query = "SELECT option_name, option_value FROM wp_options where option_name like 'test|_%' escape '|' AND option_value > ''";
global $wpdb;
$matches = $wpdb->get_results($query);
$mySettings = "[settings]\r\n";
foreach ($matches as $result){
$mySettings .= $result->option_name;
$mySettings .= ' = ';
$mySettings .= $result->option_value;
$mySettings .= "\r\n";
}
$mySettingsFileLocation = WP_PLUGIN_DIR.'/test/settings-backup.ini';
$mySettingsFile = fopen($mySettingsFileLocation, 'w');
fwrite($mySettingsFile, $mySettings);
fclose($mySettingsFile);
}