在 PHP 中将 CSV 转换为嵌套的 JSON 对象,Drupal 8

问题描述

我正在尝试将 CSV 转换为由文件中每一行的嵌套数组组成的 JSON 对象。

我已经尝试了一些类似的 SO 问题,但还没有找到非常正确的解决方案。

我正在尝试根据 CSV 的每一行中的第一个值设置一个带有少量嵌套对象的 JSON 对象。

我的名为 data_source.csv 的 CSV 文件如下所示:

Organisation ID,Organisation Name,Postcode,Industry
111,Organisation A,SW2 4DL,School
123,Organisation B,S2 5PS,School
234,Organisation C,EC2 3AD,School
...there are several more rows

我的 PHP 代码(在 Drupal 8 的控制器中):


namespace Drupal\webform_autocomplete_csv\Controller;
use Drupal\Core\Controller\ControllerBase;

class WebformAutocompleteCsvController extends ControllerBase {

  public function content() {

    //make sure file can be accessed

    if (($handle = fopen('sites/default/files/data_source.csv','r')) === false) {
      die('Error opening file');
    }

    $organisation_id = fgetcsv($handle);
    
    //take the first value on each row
    array_shift($organisation_id);

    //create an array
    $data = array();

    while ($row = fgetcsv($handle)) {
      $key = array_shift($row);
      $data[$key] = array_combine($organisation_id,$row);
    }

    $json_object = json_encode($data);

    return $json_object;

  } //close content()

}

理想情况是单个 JSON 对象和一系列嵌套对象,例如:

Object {
  111 {
       Organisation Name:Organisation A,Postcode: SW2 4DL,Industry: School
  },123 {
       Organisation Name:Organisation b,Postcode: S2 5PS,234 {
       Organisation Name:Organisation C,Postcode: EC2 3AD,Industry: School
  }
}

我的 PHP 代码设置是否尽可能有效?

当我在本地环境中运行此程序时,我收到一条错误消息,内容为:“LogicException:控制器必须返回响应([json 对象])”

所以我的 JSON 对象包含在错误消息中,这令人鼓舞,但不清楚为什么它是 LogicException 的一部分。

解决方法

也许你需要返回一个 JsonResponse

use Symfony\Component\HttpFoundation\JsonResponse;

return new JsonResponse($json_object);