Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a JavaScript literal object into Json object in PHP

I have a JS literal object string such as {name:{first:"George",middle:"William"},surname:"Washington"} and I have to convert it in Json. How can I do it using PHP?

like image 799
tic Avatar asked Sep 19 '13 15:09

tic


2 Answers

JS:

// Pretend we're POSTing this
var foo = {foo:{first:"George",middle:"William"}};

PHP:

$foo = $_POST['foo'];
$foo = json_decode( stripslashes( $foo ) );
echo $foo->first;

Credit where credit is due: https://www.youtube.com/watch?v=pORFYsgOXog

like image 160
adamj Avatar answered Sep 20 '22 20:09

adamj


If someone is still looking for an easy solution to this, as I did recently, you could check out the PHP library that I wrote: ovidigital/js-object-to-json

1) Install with composer

composer require ovidigital/js-object-to-json

2) Use it inside your project

$json = \OviDigital\JsObjectToJson\JsConverter::convertToJson($javascriptObjectString);
like image 41
ovi Avatar answered Sep 19 '22 20:09

ovi