Reputation: 5943
Problem:
Converting a PHP string to a JSON array.
I have a string in PHP that looks like this:
intelligence skin weight volume
Desired output:
Is there a way in PHP where I can convert it so it looks like this instead:
["skin", "intelligence", "weight", "volume"]
I looked at json_encode() but that only put double quotes around the keywords.
Upvotes: 0
Views: 5368
Reputation: 220
Use json_encode
$jsonVal = json_encode(explode(' ', "intelligence skin weight volume"));
Upvotes: 0
Reputation: 2787
$str="intelligence skin weight volume";
$arr=explode(' ',$str);
$json=json_encode($arr);
explode() used to split a string by a delimiter(in this senarion it is " ") Now you can encode the returend array as json.
Upvotes: 0
Reputation: 2104
first explode the string based on space. then u get an array containing individual words.then json_encode the array
$string="intelligence skin weight volume";
$array=explode(' ',$string);
$json=json_encode($array);
Upvotes: 2
Reputation: 3541
Check json_encode
This function would expect array and will convert array into json. Then use json_decode() to revert json to an array
Upvotes: 0
Reputation: 152304
If you want to create JSON array, you have to first explode your input string into an array.
Try with:
$input = 'intelligence skin weight volume';
$output = json_encode(explode(' ', $input));
Upvotes: 4