0

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 ....
6
  • 1
    You should never manually create JSON like that. Commented Jan 30, 2017 at 22:03
  • 3
    Why don't you want to use json_encode()? Commented Jan 30, 2017 at 22:04
  • @JayBlanchard I wouldn't go so far as saying never manually create JSON - there are some genuine cases that do call for it, but this certainly isn't one of them. i.e. json_encode can output the wrong kind of array in certain circumstances. Commented Jan 30, 2017 at 22:06
  • Can you post the value of $array['hits']? Use var_export() so we can paste it into a script. Commented Jan 30, 2017 at 22:09
  • 1
    FWIW, the original issue is that it adds an extra , at the very end. Everything else validates except when e.g. 'Title' contains illegal characters. (i.e. consider what happens if your title was: "Hello!" - Greetings and you. Those quotes would cause it to generate invalid JSON.) Commented Jan 30, 2017 at 22:27

1 Answer 1

5

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")
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, lesson learned! :-) just trying to figure out why the result is not printing with echo json_encode($result);
I had one mistake, title instead of Title.
My $results['hits] array gives me in this format " Array( [0] => Array ( [ID] => 69 [Title] => This is an example ", which is different from var_export. Inside my loop the values are not being associated with messages[] array. It only works/print if I do, for example, echo $value['Title'];
This is the original result that I'm receiving: github.com/algolia/…
@czmarc The difference between var_dump() and var_export() is that the latter prints in the format of PHP code, so it can be put into another script like I did in my demo. The structure of the data is the same.

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.