简体   繁体   中英

PHP: How to parse a JSON string and get the variables?

I think I have missed the obvious somewhere, what is the best way to parse parameters which are in the format...

'{"phonenumber":"123456", "mobile":"589521215", "website":"www.xfty.co.uk" }'

so that I have the individual variables?

If you have a string with JSON content:

$string = '{"phonenumber":"123456","mobile":"589521215","website":"www.xfty.co.uk"}';

You can parse it and get an associative array with json_decode :

$array = json_decode( $string, true );

And access the array with:

$array["phonenumber"] //will give back '123456'

Or, if you prefer to get an stdClass object, just use:

$object = json_decode( $string ); 

And get it with:

$object->phonenumber; //will give back '123456'

Your input looks like json format. You should use json_decode() to access it's values:

<?php
$values = json_decode('{"phonenumber":"123456","mobile":"589521215","website":"www.xfty.co.uk"}');

echo "Phonenumber:" . $values->phonenumber . "<br/>";
echo "Mobile:" . $values->mobile . "<br/>";
echo "Website:" . $values->website . "<br/>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM