1

I am writing a code of php that fetch data from dummy json api server.But i am facing this error.

Warning: Illegal string offset 'employee_name' in C:\xampp\htdocs\jsonapi.php on line 19
name: s

Warning: Illegal string offset 'employee_age' in C:\xampp\htdocs\jsonapi.php on line 21
name: s


Notice: Undefined index: employee_name in C:\xampp\htdocs\jsonapi.php on line 19
name:

Notice: Undefined index: employee_age in C:\xampp\htdocs\jsonapi.php on line 21
name:

There is my code.

<?php

$api_url = 'http://dummy.restapiexample.com/api/v1/employees';

// Read JSON file
$json_data = file_get_contents($api_url);

// Decode JSON data into PHP array
$user_data = json_decode($json_data,true);

// Cut long data into small & select only first 10 records
$user_data = array_slice($user_data,0,9);

// Print data if need to debug
//print_r($user_data);

// Traverse array and display user data

foreach ($user_data as $user) {
    echo "name: ".$user['employee_name'];
    echo "<br />";
    echo "name: ".$user['employee_age'];
    echo "<br /> <br />";

}

?>

What i should do to remove this kind of error?

2
  • This means $user_data contains strings, as opposed to objects. Commented Apr 18, 2020 at 10:15
  • what should i do? Commented Apr 18, 2020 at 10:16

1 Answer 1

3

As you can see in the fetched JSON, the actual data is contained within a data field.

So replace:

$user_data = json_decode($json_data, true);

With:

$result = json_decode($json_data, true);
$user_data = $result['data'];
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. Please consider accepthing the answer by clicking the ✔ symbol on the left.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.