Search code examples
phparraysfile

How to write extracted data from an array into a file


I am extracting data from an array with the intention to write it to a file for later use.

Extracting works fine, the results from the print_r statement give me the data I need. However the data output to the file only gets me the last value of the extracted data.

What am I missing? I have tried explode, saved the result of print_r to a string, tried output buffering start_ob() all with no result.

    $url = "http://api.discogs.com/users/xxxxxx/collection/folders/0/releases?per_page=100&page=1";
    $json = json_decode(file_get_contents($url));


//  Scan through outer loop
    foreach ($json as $inner) {

// scan through inner loop
      foreach ($inner as $value) {
//get thumb url
         $thumb = $value->basic_information->thumb;
//Remove -150 from thumb url to gain full image url
          $image =  str_replace("-150","",($thumb));

// Write it to file
     file_put_contents("file.txt",$image);
     print_r($image);

    }
    }

Solution

  • You rewrite the file, over and over, with the last data extracted. So yo need to append data to image variable and only in the end you need to put it on disk.

      $url = "http://api.discogs.com/users/xxxxxx/collection/folders/0/releases?per_page=100&page=1";
        $json = json_decode(file_get_contents($url));
    
    
    //  Scan through outer loop
        foreach ($json as $inner) {
    
    // scan through inner loop
          foreach ($inner as $value) {
    //get thumb url
             $thumb = $value->basic_information->thumb;         
    //Remove -150 from thumb url to gain full image url 
    // and append it to image
              $image .=  str_replace("-150","",($thumb));  
    // you can add ."\n" to add new line, like:
    //$image .=  str_replace("-150","",($thumb))."\n";  
    // Write it to file    
    
        }
        }
    
         file_put_contents("file.txt",$image);
         print_r($image);