簡體   English   中英

在 PHP 中將 CSV 轉換為嵌套的 JSON 對象,Drupal 8

[英]Turning a CSV into a nested JSON object in PHP, 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,
       Industry: School
  },
  234 {
       Organisation Name:Organisation C,
       Postcode: EC2 3AD,
       Industry: School
  }
}

我的 PHP 代碼設置是否盡可能有效?

當我在本地環境中運行它時,我收到一條錯誤消息,內容為:“LogicException: The controller must return an response ([the json object])”

所以我的 JSON 對象包含在錯誤消息中,這令人鼓舞,但不清楚為什么它是 LogicException 的一部分。

也許你需要返回一個JsonResponse

use Symfony\Component\HttpFoundation\JsonResponse;

return new JsonResponse($json_object);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM