我很难将所有对象数组写入.json文件.这是我的密码.使用这段代码,我刚刚得到数组的最后一个对象.json文件,但我一共有6个对象,并且成功地在终端中打印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
        );
        
        $json = json_encode($productArray);
        file_put_contents("output.json", $json);
    
      }

推荐答案

因为您正在循环中写入文件,所以每次都会覆盖其内容.

要将所有数据写入一个文件,并使其写入一个有效的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);

Php相关问答推荐

如何使用动态键来获取Laravel Livewire表格中的错误?

在没有谷歌云客户端PHP库的情况下将图像上传到PHP中的Google存储API?

如何修复条带元素中的错误&&客户端_机密&

在WooCommerce中添加基于类别的固定费用

EBay Inventory API createOrReplaceInventoryItem出错

使用列入黑名单的单词和自定义业务逻辑的组合将特定的子字符串包装在HTML标记中

使用php创建表格和插入数据

WooCommerce:如果购物车中已存在产品,则增加购物车商品数量

如果 Select 的县不是store 所在的县,如何隐藏本地自提?

PHP 中使用 JSON 的自定义会话处理程序会因错误而 destruct 会话

为什么 debug_backtrace() 不返回任何内容?

加载 Xdebug PHP 7.4.0 失败

PHP 中的curl -F request=@file.xml

WooCommerce订单支付页面上的附加支付订单按钮

如何在PHP中对多个脚本调用进行排队?

如何使用在产品快速编辑菜单前端的自定义框中 Select 的值更新 woocommerce 产品属性值?

如何从此字符串创建 Carbon 对象:2022-06-21T05:52:46.648533678Z?

Laravel Docker 几个数据库

laravel 中的 OrderBy json 列

使用 Eloquent 更新现有的外键值