Scott B
Scott B

Reputation: 40157

Adding line breaks to output file via fwrite

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

Upvotes: 4

Views: 23681

Answers (3)

KingCrunch
KingCrunch

Reputation: 131891

You can use the platform dependent constant PHP_EOL instead

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

Upvotes: 5

genesis
genesis

Reputation: 50976

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

Upvotes: 0

user703016
user703016

Reputation: 37945

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";

Upvotes: 20

Related Questions