1

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

}

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.

1 Answer 1

1

Maybe you need to return a JsonResponse

use Symfony\Component\HttpFoundation\JsonResponse;

return new JsonResponse($json_object);
Sign up to request clarification or add additional context in comments.

1 Comment

That sorted it. Thank you @2pha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.