1

I could not convert the JSON string to array using PHP. Here is my code:

$edu=$_POST['edu'];
echo ($edu);

The above line is giving the below output.

'[{"uname":"univ1","year":"2017","description":"hello"},{"uname":"univ2","year":"2016","description":"hello des"}]' 

I need to convert this to array using below code.

$eduArr=json_decode($edu,true);
print_r($eduArr);

But here I am getting the output as (empty). I need to convert the above string to array.

6
  • $edu = trim($_POST['edu'], "'"); maybe Commented May 25, 2017 at 7:51
  • what's the json_last_error says ? Commented May 25, 2017 at 7:51
  • @hassan : how to check the error ? Commented May 25, 2017 at 7:52
  • 2
    php.net/json_last_error Commented May 25, 2017 at 7:52
  • 2
    That string decodes just fine. Add echo json_last_error_msg(); after your json_decode() and see if you get some error message that will help Commented May 25, 2017 at 7:55

2 Answers 2

2

You json string is not a valid json. It have extra ' on both side of the string.

From your echo result the ' is output on each side of the string. For a json string the ' shoudn't be there.

You can check the live demo here have a good understanding.

$eduArr=json_decode(trim($edu, '\''),true);
print_r($eduArr);
Sign up to request clarification or add additional context in comments.

4 Comments

if I will have "[{\"uname\": \"Trident Academy Of Creative Technology\", \"year\": \"2011\", \"description\": MCA\"}]" data then how to trim.
You needn't. Have you try it?
No,I have not tried but the data like this will come then how to get the expected output.
It's because your json string is invalid. MCA\" should \"MCA\" You can check it here
0

it's work for me:

$json = '[{"uname":"univ1","year":"2017","description":"hello"},{"uname":"univ2","year":"2016","description":"hello des"}]';
$arr = json_decode($json);
print_r($arr);

1 Comment

I know its working while direct string is given but while I am getting the data in post method in this case not working

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.