0

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!

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

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.