Ahmad Badpey
Ahmad Badpey

Reputation: 6622

convert query String to json in php

I send a QueryString formatted text like bellow to a php Script via Ajax:

title=hello&custLength=200&custWidth=300  

And I want to convert this text to a JSON Object by this result in PHP:

{
    "title" : "hello",
    "custLength" : 200,
    "custWidth" : 300
}

How can i do that. Does anyone have a solution?

Edit : In fact i have three element in a form by title , custLength and custWidth names and i tried to send these elements via serialize() jquery method as one parameter to PHP script.

this code is for Send data to php:

    customizingOptions  =   $('#title,#custLength,#custWidth').serialize();

$.post('cardOperations',{action:'add','p_id':p_id,'quantity':quantity,'customizingOptions':customizingOptions},function(data){

if (data.success){

    goBackBtn('show');

    updateTopCard('new');           
}                   

},'json');

in PHP script i used json_encode() for convert only customizingOptions parameter to a json.
But the result was not what I expected and result was a simple Text like this:

"title=hello&custLength=200&custWidth=300"

Upvotes: 4

Views: 12482

Answers (3)

Portalbendarwinden
Portalbendarwinden

Reputation: 121

I realize this is old, but I've found the most concise and effective solution to be the following (assuming you can't just encode the $_GET global):

parse_str('title=hello&custLength=200&custWidth=300', $parsed);

echo json_encode($parsed);

Should work for any PHP version >= 5.2.0 (when json_encode() was introduced).

Upvotes: 12

Junaid Ahmed
Junaid Ahmed

Reputation: 695

$check = "title=hello&custLength=200&custWidth=300";
$keywords = preg_split("/[\s,=,&]+/", $check);
$arr=array();
for($i=0;$i<sizeof($keywords);$i++)
{
$arr[$keywords[$i]] = $keywords[++$i];
}
$obj =(object)$arr;
echo json_encode($obj);

Try This code You Get Your Desired Result

Upvotes: 7

pes502
pes502

Reputation: 1597

The easiest way how to achiev JSON object from $_GET string is really simple:

json_encode($_GET)

this will produce the following json output:

{"title":"hello","custLength":"200","custWidth":"300"}

Or you can use some parse function as first (for example - save all variables into array) and then you can send the parsed output into json_encode() function.

Without specifying detailed requirements, there are many solutions.

Upvotes: 3

Related Questions