PHP:从像String这样的Python字典中获取字符串

时间:2013-10-10 09:48:07

标签: php

我有一个字符串:

{"Url":"http://localhost","DBName":"John_db","DBUser":"admin","Pass":"a"}

现在使用此字符串我想要URL,DBname,DBuser并将它们传递给单独的变量,如:

$DBName =  'John_db';
$DBUser =  'admin';
$Url    =  'http://localhost';
$Pass   = 'a';

我是PHP的新手,找不到任何解决方案来实现这一目标,有人可以帮助我吗?

5 个答案:

答案 0 :(得分:2)

“此字符串”是JSON对象。使用json_decode()获取包含所有值的数组,然后从那里获取它。

$str = '{"Url":"http://localhost","DBName":"John_db","DBUser":"admin","Pass":"a"}';
$out = json_decode( $str, true );

$out的结尾如下:

Array
(
    [Url] => http://localhost
    [DBName] => John_db
    [DBUser] => admin
    [Pass] => a
)

答案 1 :(得分:2)

您并不需要将每个变量分成单个变量。您可以将JSON解码为数组或对象:

$str = '{"Url":"http://localhost","DBName":"John_db","DBUser":"admin","Pass":"a"}';
$arr = json_decode( $str, true );

现在你有一个包含所有变量的关联数组:

Array(
  [ Url ] => "http://localhost",
  [ DBName ] => "John_db",
  ...
)

如果您没有为json_decode()指定第二个参数,您将获得一个常规对象:

$obj = json_decode( $str );
echo $obj->Url; // http://localhost
echo $obj->DBName; // John_db

参考文献 -

答案 2 :(得分:2)

$ar = json_decode( '{"Url":"http://localhost","DBName":"John_db","DBUser":"admin","Pass":"a"}', 1 );
foreach ($ar as $k => $a) {
   $$k = $a;
}

现在你应该填补你的vars。

此处的工作代码:http://codepad.org/Do9ixqfN

答案 3 :(得分:1)

使用像这样的json_decode函数:

<?
$string = '{"Url":"http://localhost","DBName":"John_db","DBUser":"admin","Pass":"a"}';
$array = json_decode( $string, true );

print_r($array);
?>

WORKING CODE

答案 4 :(得分:0)

该字符串是一个JSON对象,您可以使用json_decode将该字符串转换为关联数组。