Home > Software design >  how to write multiple arrays of objects into json file using php?
how to write multiple arrays of objects into json file using php?

Time:07-06

I am having difficulty to write all of the array of objects into .json file. Here is my code. Using this code, I am just getting last object of array in .json file but I have 6 objects in total and successfully array is printing in terminal. Can anyone help me please? Thanks

foreach($crawler as $node) {
    
        $title = $node->filter('h3')->text();
        $img = $node->filter('img')->attr('src');
        $color = $node->filter('div.my-4 div.flex div.px-2 span')->attr('data-colour');
        $capacity = $node->filter('span.product-capacity')->text();
        $availibity = $node->filter('div.text-sm')->text();
        $shippingText = $node->filter('div.bg-white > div')->last()->text();
        $shippingDate = $node->filter('div.bg-white > div')->last()->text();
        $productArray = array(
    
          'title' => $title,
          'price' => 12,
          'imageUrl'=> 'https://www.magpiehq.com/developer-challenge/smartphones/'.$img,
          'capacityMB' => $capacity,
          'colour' => $color,
          'availabilityText' => $availibity,
          'shippingText' =>$shippingText,
          'shippingDate' =>$shippingDate
        );
        
        $json = json_encode($productArray);
        file_put_contents("output.json", $json);
    
      }

CodePudding user response:

Because you're writing to the file inside the loop, you keep overwriting its contents every time.

To write all the data to a file, and make it write a valid JSON entity which will be decodable again later, you need to construct a single array containing all your product data, and then encode and write that array to the file once, after the loop has ended.

For example:

$products = array();

foreach($crawler as $node)
{
    $title = $node->filter('h3')->text();
    $img = $node->filter('img')->attr('src');
    $color = $node->filter('div.my-4 div.flex div.px-2 span')->attr('data-colour');
    $capacity = $node->filter('span.product-capacity')->text();
    $availibity = $node->filter('div.text-sm')->text();
    $shippingText = $node->filter('div.bg-white > div')->last()->text();
    $shippingDate = $node->filter('div.bg-white > div')->last()->text();
    
    $productArray = array (
          'title' => $title,
          'price' => 12,
          'imageUrl'=> 'https://www.magpiehq.com/developer-challenge/smartphones/'.$img,
          'capacityMB' => $capacity,
          'colour' => $color,
          'availabilityText' => $availibity,
          'shippingText' =>$shippingText,
          'shippingDate' =>$shippingDate
    );
    
    $products[] = $productArray; //add the current item to the overall array
}

//encode all the data at once, and then write it to the file
$json = json_encode($products);
file_put_contents("output.json", $json);
  • Related