1

I have some strings, the format like this

name=bob&age=10&sex=male&weight=80&...

And I want to convert it to json format

{
  "name":"bob",
  "age":"10",
  "sex":"male",
  "weight":"80",
  //and more
}

I wrote some codes, but I don't know how to continue

$co="name=bob&age=10&sex=male&weight=80&...";
$toarray = explode("&", $co);

Does someone give some tips? Many thanks.

1

2 Answers 2

6

You can use parse_str for the same,

parse_str("name=bob&age=10&sex=male&weight=80", $output);
echo json_encode($output);
print_r($output); // if you need normal array.

Explanation: It will capture all URL string as an array to output. As I see you need JSON string I used json_encode to convert array to string.

Here is link you can refer for details.

Demo.

Sign up to request clarification or add additional context in comments.

Comments

0
$co="name=bob&age=10&sex=male&weight=80&...";
$result = [];
foreach (explode('&', $co) as $item) {
    list($key, $value) = explode('=', $item);
    $result[$key] = $value;
}
echo json_encode($result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.