Skip to content
Advertisement

Turning a CSV into a nested JSON object in PHP, Drupal 8

I’m trying to turn a CSV into a JSON object made of nested arrays for each row within the file.

I’ve tried a handful of similar SO questions but haven’t found quite the right solution.

I’m attempting to set up a JSON object with a handful of nested objects, based on the first value in each row of the CSV.

My CSV file, titled data_source.csv looks like:

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

My PHP code (in a controller in Drupal 8):

namespace Drupalwebform_autocomplete_csvController;
use DrupalCoreControllerControllerBase;

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()

}

The ideal situation would be a single JSON object with a series of nested objects, like:

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

Is my PHP code set up as effectively as possible?

When I run this on my local environment, I receive an error message that reads: ‘LogicException: The controller must return a response ([the json object])’

So my JSON object is included in the error message, which is encouraging but it’s unclear why it’s part of a LogicException.

Advertisement

Answer

Maybe you need to return a JsonResponse

use SymfonyComponentHttpFoundationJsonResponse;

return new JsonResponse($json_object);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement