Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Get string from Python dictionary like String

Tags:

php

I have a string like:

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

Now using this string I want URL, DBname, DBuser and pass them to separate variables like:

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

I am new to PHP, and can't find any solution to achieve this, can anybody help me in this?

like image 702
OpenCurious Avatar asked Dec 06 '25 21:12

OpenCurious


1 Answers

You don't really need to split each one into individual variables. You could just decode that JSON into an array or object:

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

Now you have an associative array containing all of the variables:

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

If you don't specify the second parameter to json_decode(), you'll get a regular object:

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

References -

  • json_decode()
like image 86
Lix Avatar answered Dec 09 '25 13:12

Lix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!