Chamara Maduranga
Chamara Maduranga

Reputation: 256

How to append the two lines string in php json response

{
    "employees": [{
        "name": "Chicken Shawarma",
        "price": "510.00",
        "nutrients": "A
        B "
    }]
}

this is the my json response , In My app i setup a two line record for "nutrients". Ex :

A
B

this vale saved in database without any issue (My SQL), now i want display the "nutrients" data as a two line record. but its displaying below error

SyntaxError: unterminated string literal

if you have any idea please share with me.

this is the my server side code

        if ($itemInfo->num_rows() == 1) {
        $row = $itemInfo->row_array();       
        $json_arr = $_GET['callback'] . '(' .
                "{'name' : '" . $row['name'] . "',"
                . "'nutrients' : '" . $row['nutrients'] . "',"
                . "'img' : '" . $row['img'] . "'}" . ')';
    } else {
        $json_arr = json_encode(array('status' => 'N'));
    }

    echo $json_arr;

this is the my client side code

    $http.jsonp(full_url).success(function (data) {
        $scope.item = data ;
    });

Upvotes: 0

Views: 62

Answers (1)

Ivan Velichko
Ivan Velichko

Reputation: 6709

Your main problem is making a JSON response by concatenating strings. In such case you miss required encodings/escaping and so on. So, first of all you should create an associative array and then do $json_arr = $_GET['callback'].'('.json_encode($your_json_like_array).')'; exactly like in the else clause.

Resulting code should look like this:

$json_arr = array(
    'name' => $row['name'], 
     ..., 
    'nutrients' => $row['nutrients']
);
$json_arr = $_GET['callback'].'('.json_encode($json_arr).')';

Upvotes: 2

Related Questions