首页 > 解决方案 > 在 PHP,Drupal 8 中将 CSV 转换为嵌套的 JSON 对象

问题描述

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

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

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

我的 CSV 文件,标题为 data_source.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,
       Industry: School
  },
  234 {
       Organisation Name:Organisation C,
       Postcode: EC2 3AD,
       Industry: School
  }
}

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

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

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

标签: phpjsoncsvdrupal

解决方案


也许你需要返回一个JsonResponse

use Symfony\Component\HttpFoundation\JsonResponse;

return new JsonResponse($json_object);

推荐阅读