Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

5 Answers

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));
share|improve this answer
add comment

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);
share|improve this answer
add comment

Check json_encode

This function would expect array and will convert array into json. Then use json_decode() to revert json to an array

share|improve this answer
add comment
$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.

share|improve this answer
add comment

Use json_encode

$jsonVal = json_encode(explode(' ', "intelligence skin weight volume"));
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.