Search code examples
phpjsonforeach

Manually created JSON string is not valid


I created a manual loop to form a json that is used by another API on a project that I am starting, please find below.

The problem is that the API is not recognising my json output. I checked the result of my loop and it looks fine.

If I copy and paste directly my result (echo) it works fine, but through my loop it is not working. Does anyone have any idea?

foreach ($array['hits'] as $key => $value) {

    $message = $message.'{
            "title":"'.$value['Title'].'",
            "image_url":"'.$value['image'].'",
            "subtitle":"'.substr($value['Detail'],0,120).'",
            "buttons":[
                    {
                            "type":"web_url",
                            "url":"'.SITE_ROOT_URL.$value['URL'].'?utm_source=chatbot",
                            "title":"Leia mais"
                    }
            ]
    },';

}

$message = '{"messages": [
             {
                     "attachment":{
                             "type":"template",
                             "payload":{
                                     "template_type":"generic",
                                     "elements":['.rtrim($message,",").']
                             }
                     }
             }
     ]
}';

echo $message;

The output of var_export($array['hits']) looks like:

array ( 0 => array ( 'ID' => '69', 'Title' => 'This is an example', 'URL' => 'example/1', 'Detail' => 'Some description here...', 'image' => 'image1.png', 'objectID' => '75877631') ), 1 => array ....

Solution

  • Don't generate the JSON by hand. Build the array and then use json_encode().

    $messages = array();
    foreach ($array['hits'] as $key => $value) {
        $messages[] = array(
            'title' => $value['Title'],
            'image_url' => $value['image'],
            'subtitle' => substr($value['Detail'], 0, 120),
            'buttons' => array(
                array(
                    'type' => 'web_url', 
                    'url' => SITE_ROOT_URL.$value['URL'].'?utm_source=chatbot', 
                    'title' => "Leia mais"
                )
            )
        );
    }
    $result = array(
        'messages' => array(
            'attachment' => array(
                'type' => 'template',
                'payload' => array(
                    'template_type' => 'generic',
                    'elements' => $messages
                )
            )
        )
    );
    echo json_encode($result);
    

    DEMO

    Notice how the elements of your hand-constructed JSON arrays and objects map directly to PHP arrays. If the JSON contains:

    { "something": "something else" }
    

    the corresponding PHP is:

    array("something" => "something else")