ss412
ss412

Reputation: 1

How to parse a json object into a url parameter string in PHP?

I have the following json encoded object:

{"username":"my_username","email":"my_email","password":"12345678","confirm_password":"12345678"}

and I want to convert this into url string so I can use it with my REST API function for example like this one:

search?search=asdadd%2C+United+Kingdom&type=tutor

I have found many functions in javascript to do this but I haven't been able to find anything in PHP. What is the function in PHP to do this?

Upvotes: 0

Views: 2938

Answers (1)

Lansana Camara
Lansana Camara

Reputation: 9873

The following query string:

?username=my_username&email=my_email&password=12345678&confirm_password=12345678

.. will turn into:

{"username":"my_username","email":"my_email","password":"12345678","confirm_password":"12345678"}

If you use json_enconde.

To reverse the process, you need to use json_decode as well as http_build_query.

First, turn the JSON into an associative array with json_decode:

$json = '{"username":"my_username","email":"my_email","password":"12345678","confirm_password":"12345678"}';

$associativeArray = json_decode($json, true);

Now use http_build_query with the new associative array we've built:

$queryString = http_build_query($associativeArray);

Result: username=my_username&email=my_email&password=12345678&confirm_password=12345678.

Upvotes: 2

Related Questions