SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    Now available in Orange Tijmen's Avatar
    Join Date
    Jul 2004
    Location
    The Netherlands
    Posts
    1,469
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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.

    Code
    Code:
    $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\n';
    }
    
    $json_file .= '} }';
    
    fwrite($fp, json_encode($json_file));
    fclose($fp);
    Output
    Code:
    {\"\"country\":\"Afghanistan\", \"alphacode\":\"AF\", \"lat\":\"33, \"long\":65\\r\\n\"
    After some search on Google I found this line of code thats supposed to fix the adding of slashes. But it doesnt help either.

    Code:
    if (get_magic_quotes_runtime())
        set_magic_quotes_runtime(0);
    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?
    Travel Photos on Flickr - Twitter

    “Never give up. Never surrender”

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    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\n is the literal text \r\n.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •