Passing structure content to an API page

Hello, I am trying to store some fields on an API page to use it with Javascript and populate a modal.
It all works fine, but I can’t seem to figure the way to pass the structure fields without getting an error (400 on clicking the overlay trigger when trying to access the api page).

Does someone know how to fix this?

Thanks a lot in advance

Here’s my code for the api.php


<?php

header('Content-type: application/json; charset=utf-8');

$data = $pages->find('opportunities')->children()->listed()->flip();
$json = array();

foreach($data as $article) {

  $num = $article->number();
  $date = $article->createdAt()->toDate('y-m-d'); // get the date in Y-m-d format
  $items = $article->textContent()->toStructure();
  $year = date('y', strtotime($date)); // extract the year from the date
  $month = date('m', strtotime($date)); // extract the month from the date
  $day = date('d', strtotime($date)); // extract the day from the date

  $words = explode(" ", $article->role());
  $acronym = "";

    foreach ($words as $w) {
      $acronym .= mb_substr($w, 0, 1);
    }

  $content = "";
      foreach ($items as $item) {
          $content .= '<div class="bb b--black-10 pv3">';
          $content .= '<p class="mb2">' . $item->heading()->value() . '</p>';
          $content .= '<div>' . $item->cont()->value() . '</div>';
          $content .= '</div>';
      }

  $json[] = array(
    'title' => (string)$article->title(),
    'num' => str_pad((string)$article->number(), 2, '0', STR_PAD_LEFT),
    'content' => $content,
    'role' => (string)$article->role(),
    'uid' => (string)$article->uid(),
    'codeDate' => (string)$article->createdAt()->toDate('my'),
    'dateYear' => (string)$year,
    'dateMonth' => (string)$month,
    'dateDay' => (string)$day,
    'acronym' => (string)$acronym,

  );

}

echo json_encode($json);

?>

I think the problem is probably your HTML bit, try using the JSON_UNESCAPED_SLASHES flag when json_encoding.

Thanks for answering.
I tried echo json_encode($json, JSON_UNESCAPED_SLASHES); with no luck.
But thanks anyway for the help!

Is the json content accessible if you open it in the browser?

Good point.
I am actually getting a ‘Invalid structure data for “textcontent” field on parent’ when trying to access the api on the browser, in case you meant this.

Oh, one of the pages didn’t have any content introduced, and this caused the error. Silly me.
Thanks!