简体   繁体   English

PHP:如何解析JSON字符串并获取变量?

[英]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: 如果您的字符串包含JSON内容:

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

You can parse it and get an associative array with json_decode : 您可以解析它并使用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: 或者,如果您希望获取stdClass对象,则只需使用:

$object = json_decode( $string ); 

And get it with: 并获得它:

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

Your input looks like json format. 您的输入看起来像json格式。 You should use json_decode() to access it's values: 您应该使用json_decode()来访问其值:

<?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/>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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