Reputation: 341
I generate some JS objects strings in PHP because all of the variables i need are there, instead of passing them to js and generate the object there:
$results[] = "{value:" . $data . ",color:\"rgba($aa,$ab,$ac," . Config::$TRANSPARENCY_B . ")\",highlight:\"rgba($ba,$bb,$bc," . Config::$TRANSPARENCY_B . ")\",label:\"" . $entry->getDate() . "\"}";
Now i want to pass the finished result list of JS object strings to JS in order to display it. The resulting structure should be like: [{object1}, {object2}, ...]
In order to achieve this i use htmlspecialchars(json_encode($result), ENT_QUOTES, "UTF-8")
However this ends up in something of the structure: {"{object1}", "{object2}", ...]
, which of course won't work. How can i manage to throw away the useless enclosing "
? I had a look through json_encode()
and htmlspecialchars()
but none of the parameters there seems to fit.
Any ideas? Thanks!
EDIT: Turns out i am completely dumb. Of course i should pack up some real objets and not a string representing them.. THANKS!
Upvotes: 0
Views: 27
Reputation: 36511
You would be better off not manually making JSON out of strings and use the json_encode
function to do it for you:
$results[] = array(
'value' => $data,
'color' => "rgba($aa,$ab,$ac," . Config::$TRANSPARENCY_B . ")",
'highlight' => "rgba($ba,$bb,$bc," . Config::$TRANSPARENCY_B . ")",
'label' => $entry->getData()
);
echo json_encode($results);
Upvotes: 2
Reputation: 318302
Why not just create real objects, that way encoding them as JSON is easy
$obj = new stdClass;
$obj->value = $data;
$obj->label = $entry->getDate();
$results[] = $obj;
echo json_encode($results);
Associative arrays would also be outputted as "objects" in JSON, and is probably easier
Upvotes: 2