Invalid argument supplied for foreach() - Array

Asked

Viewed 746 times

0

Good morning.

I’m trying to consume a json in PHP but I’m having this problem:

Warning: Invalid argument supplied for foreach() in D: xampp htdocs api consumir index.php on line 7

Array Code - JSON

http://jsfiddle.net/svbL9cjb/

PHP code

<?php
$json_file = file_get_contents("http://localhost/api/carne/retornofim.php");

$json_str = json_decode($json_file, true);
$itens = $json_str['nodes'];

foreach ( $itens as $e ) 
{ 
    echo $e['title']."<br>"; 
}
?>

http://phpfiddle.org/main/code/34uy-zf37

Att

1 answer

1


Warning: Invalid argument supplied for foreach() in D: xampp htdocs api consumir index.php on line 7

This message occurs because the variable $itens is not an array, or a possible object to be used inside the foreach, and analyzing your json does not exist these keys that are in the code (nodes or title).

So before using the foreach, or trying to get some key put:

$json_file = file_get_contents("http://localhost/api/carne/retornofim.php");
var_export($json_file);
die();

So you will be able to see the return before manipulating the data.

To show more information:

header('Content-Type: text/plain');
error_reporting(~0); ini_set('display_errors', 1);
$url = 'http://localhost/api/carne/retornofim.php';
$results = file_get_contents($url);
var_dump($http_response_header, $results);
die();

Source: PHP: "file_get_contents()" returning NULL from content-verified URL

  • now returned me NULL ?

  • First you have to check if the url is working, put it directly in the http browser://localhost/api/meat/return.php, if it shows you the result is because it is working.

  • https://prnt.sc/j9fv8q JSON returns normal at http:/localhost/api/meat/return.php Now I need to pull JSON data to HTML

  • I changed the answer, you put it like that, and yet you’re showing nothing?

  • http://prntscr.com/j9fy38 Me returned NULL.

  • I put a code so you can debug why it’s not coming.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.