Malloc
Malloc

Reputation: 16276

How to transform a JSON String into PHP array

A JSON string is sent via a HTTP request to my webservice, it looks like this:

[\"Mairie\",\"Préfectures et sous-préfectures\"]

How can i do to make a simple php array in which i can perform php arrays functions such as implode.

I tried this but it didn't transform the JSON String into an array:

    $list=json_decode($_POST["The_JSON_Parameter"],true);

EDIT:

var_dump(json_decode($_POST["The_JSON_Parameter"], true));   
$var=json_decode($_POST["The_JSON_Parameter"],true);
$in_list = "'".implode("','", $var)."'";
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $in_list);//in the text file i got this empty string: ''

Upvotes: 1

Views: 201

Answers (2)

anubhava
anubhava

Reputation: 784958

If you try this code:

$str = "[\"Mairie\",\"Préfectures et sous-préfectures\"]";
var_dump(json_decode($str,true));

You will get:

array(2) {
  [0]=>
  string(6) "Mairie"
  [1]=>
  string(33) "Préfectures et sous-préfectures"
}

So are you sure your $_POST["The_JSON_Parameter"] has the same value i.e. a string literal "[\"Mairie\",\"Préfectures et sous-préfectures\"]" ?

Upvotes: 0

xdazz
xdazz

Reputation: 160833

$var = "[\"Mairie\",\"Préfectures et sous-préfectures\"]";
var_dump(json_decode($var, true));

/*result:
array(2) {
  [0]=>
  string(6) "Mairie"
  [1]=>
  (33) "Préfectures et sous-préfectures"
}
*/

Works fine, please do var_dump($_POST["The_JSON_Parameter"])

Upvotes: 3

Related Questions