Adding line breaks to output file via fwrite

半世苍凉 提交于 2019-12-01 21:08:50

问题


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?

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

回答1:


Special characters like \r and \n do not get interpreted in single quotes. Use double quotes instead.

$mySettings = "[settings]\r\n";

And

$mySettings .= "\r\n";



回答2:


You can use the platform dependent constant PHP_EOL instead

$mySettings = '[settings]' . PHP_EOL;
// ..
$mySettings .= PHP_EOL;



回答3:


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


来源:https://stackoverflow.com/questions/6683595/adding-line-breaks-to-output-file-via-fwrite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!