0

I'm having some problems getting the data through my PHP loop.

<?php
$url = 'https://www.fibalivestats.com/data/1653309/data.json';
$content = file_get_contents($url);
$json = json_decode($content, true);
?>

<?php 


foreach($json['totallds']['sPoints'] as $item); {
        
    echo $item;
}

?>

The error I'm getting is an array to string conversion error. What I'm trying to get is the data from the sPoints array that will give me a Top 5 points scorers for a basketball game.

I'll build a table for this in HTML later but for now, it's not displaying the data at all and I'm getting errors. I feel like I may have confused arrays and strings too. Any thoughts about what I'm doing wrong? JSON file can be found in the $url variable.

Also if it helps, here's the link to where I have gotten the data from and what context the Top 5 is from https://www.fibalivestats.com/u/NSS/1653309/lds.html

Thanks!

3 Answers 3

1

Your $item is an array, so you can't just echo it like that. You can, however, echo its columns, for example:

foreach($json['totallds']['sPoints'] as $item) {
    echo $item['firstName'] . ' ' . $item['familyName'];
}

Notice the removed semicolon between the foreach () and {.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for this! I get one player name out of that echo.I only get the last player. I don't get all five players. Is there any way to do this?
Updated. You had a typo there - a semicolon after the foreach, which made it go nuts :)
Perfect! It works a charm. Thanks heaps! This should work in a table I'm guessing? I'm concerned it might output all of the results into one table cell.
You're welcome. I deleted my previous comment, because you also need to split it into separate rows if you need to. Please open another question if you struggle with displaying a table out of this data.
0

Well, array to string conversion error means you're trying to echo an array.

If you see the return of the url you are looking at, you can verify that the "sPoints" key returns an array with several objects.

enter image description here

Try to change echo to print_r or var_dump to view entire data or complete your business logic.

Comments

0

Try changing:

echo $item;

to:

var_dump($item);

1 Comment

Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues.

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.