如何使用PHP将多个对象数组写入JSON文件?

3

我遇到了困难,无法将所有对象数组写入.json文件。以下是我的代码。使用该代码,我只能在.json文件中获取数组的最后一个对象,但我总共有6个对象,并且成功将数组打印到终端。请问有人能帮帮我吗?谢谢。

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

你的 file_put_contents() 调用在循环内部,因此每次迭代都会覆盖前一个。在循环内部构建一个数组的数组,然后在循环结束后放置你的 file_put_contents()。 - Alex Howansky
@AlexHowansky 我刚刚尝试了一下,它仍然将最后一个对象显示为 json 文件,而不是第六个。 - ku234
@ku234,也许你没有完全理解它。请看下面答案中的例子。 - ADyson
你能给我一些关于如何构建二维数组的提示吗? - ku234
@ADyson 当然,我很期待。谢谢。 - ku234
它已经在那里了,你现在就可以看一下 :-) - ADyson
1个回答

1

由于您正在循环内部写入文件,每次都在覆盖其内容。

要将所有数据写入文件,并使其编写有效的JSON实体以便稍后可以解码,您需要构造包含所有产品数据的单个数组,然后在循环结束后一次性对该数组进行编码并写入该文件。

例如:

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

非常感谢。现在可以工作了。 - ku234
好的。你明白为什么吗? - ADyson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接