Json file write with slashes and newlines?

I’m trying to convert a big json file into a smaller one. The original file contains lots of data I don’t need, so I’m trying to grab the fields I need and write them into a new file.

The grabbing the data and writing it into new file works fine. The part that I can’t get to work, is added newlines into the file and preventing the slashes from appearing in the file (the slashes don’t exist in the original file).

This is the code and the output I get now.


$test = file_get_contents("rows.json");
$json = json_decode($test);
$fp = fopen('results.json', 'w');

$json_file .= '{ "country_list": {"';

foreach ($json->data as $val) {
     $json_file .= '"country":"'.$val[8].'", "alphacode":"'.$val[9].'", "lat":"'.$val[12].'", "long":"'.$val[13].'"\\r\

$json_file .= '} }';

fwrite($fp, json_encode($json_file));


{\\"\\"country\\":\\"Afghanistan\\", \\"alphacode\\":\\"AF\\", \\"lat\\":\\"33, \\"long\\":65\\\\r\\\

After some search on Google I found this line of code thats supposed to fix the adding of slashes. But it doesnt help either.

if (get_magic_quotes_runtime())

Any idea how to prevent the slashes form showing up in the file, and getting the newline to work. Right now they just show up in the json file itself?

I’m not sure about the slashes, I assumed they were coming from magic quotes too.

But about the newlines, you just need to enclose them in double quotes instead of single quotes where you build the string. Escape sequences are only interpreted when inside double quotes. In single quotes, \r
is the literal text \r