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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:59:24  来源:igfitidea点击:

Adding line breaks to output file via fwrite

phpfwrite

提问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 \rand \ndo 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_EOLinstead

您可以使用该平台相关的常数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';

put it in double quotes

把它放在双引号中

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);
}