Help me with a php foreach array

Asked

Viewed 715 times

2

Good afternoon,

I’m using PHP’s Curl to get a json from an api. The data is being stored correctly in a variable. But when I try to display the data with an error foreach on the line where the foreach:

The json that comes from the site is like this:

[{"Nome":"Sabrina","Sobrenome":"Freitas"}, 
 {"Nome":"Maria","Sobrenome":"Sebastiana"}, 
 {"Nome":"Evandro","Sobrenome":"Martins"}]

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://www.teste.com.br/json);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


$data = array();

$data = curl_exec($ch);

curl_close($ch);


foreach($data as $key => $valor){


    echo "Nome: $valor->Nome <br>";
    echo "Sobrenome: $valor->Sobrenome <br><hr>";


}

?>

PHP returns this error to me:

Warning: Invalid argument supplied for foreach() in /Storage/ssd3/794/5409794/public_html/index.php on line 17

Does anyone know where I’m going wrong? Thanks in advance

  • but already comes in json format or failed to convert?

  • I think you forgot to close the single quotes on the curl_setopt line

  • try to concatenate the value in foreach like this: echo "Nome: ".$valor->Nome."<br>";

  • rray ?? Already comes in json format

  • adventistaam ?? concatenating did not work

  • I think you have to do this: json_decode($data, true); before making the foreach, moreover, it is always good to check whether it has given to do the foreach... like: if(count($data)) {...}

Show 1 more comment

2 answers

2

Being brief, PHP does not recognize the contents of $data as an object, nor as an array (referenced in foreach), for this you need to convert the string received to the correct format:

$data = array();

$data = curl_exec($ch);
$data = json_decode($data, true); //novo código
curl_close($ch);


foreach($data as $key => $valor){


    echo "Nome: {$key["Nome"]} <br>";
    echo "Sobrenome: {$key["Sobrenome"]} <br><hr>";


}

so you can iterate the object as much as array. You can use var_dump() before the foreach to view the content and type of $data, so it becomes easier to find the problem.

  • Mauro, when I do a var_dump() it informs that it is a string ({string(193387)) keeps giving error in the foreach even doing what you said

  • I updated, take a look.

  • When I give one (echo $data ) all data appears

  • Rodrigo, you need to run the var_dump() before the foreach and after the new code $data = json_decode();

  • right, first I made $data = json_decode($data,true) then I did the var_dump(&data) and the result = NULL

  • without making the $data = json_decode($data,true) and calling the var_dump($data) the result is string(193387)"[{"First name":"Sabrina","Last name":"Freitas"}, {"First name":"Maria","Last name":"Sebastiana"}, {"First name":"Evandro","Last name":"Martins"}]"

  • In case you can pass the link of the site that provides the API, it would be better to be able to help, I am simulating on my machine with this same code and it is working.

  • guy the link is restricted and to access need login and password.

  • If I could change the password I would pass but I can’t control it unfortunately

  • Try to redo the code according to the answer, without var_dump. I refreshed it again.

  • this giving error in the foreach line

Show 6 more comments

1


Your json can return NULL for several reasons:

I will list them below:

JSON_ERROR_DEPTH // A profundidade máxima da pilha foi excedida

JSON_ERROR_STATE_MISMATCH // JSON inválido ou mal formado

JSON_ERROR_CTRL_CHAR // Erro de caractere de controle, possivelmente codificado incorretamente

JSON_ERROR_SYNTAX // Erro de sintaxe

JSON_ERROR_UTF8 // caracteres UTF-8 malformado , possivelmente codificado incorretamente

See more in the manual.

To find out what the problem you can do as follows:

$data = curl_exec($ch);
$data = json_decode($data, true);
curl_close($ch);
switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - No errors';
    break;
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - Underflow or the modes mismatch';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
    break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
    break;
    case JSON_ERROR_UTF8:
        echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
    break;
    default:
        echo ' - Unknown error';
    break;
}

Most of the time the problem is related to JSON_ERROR_UTF8. And if so, there are some ways to try to solve it. How:

$data = curl_exec($ch);
$data = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($data));
$data = json_decode($data, true);
curl_close($ch);

There is also this script:

function safe_json_encode($value, $options = 0, $depth = 512){ 
    $encoded = json_encode($value, $options, $depth); 
    switch (json_last_error()) { 
        case JSON_ERROR_NONE: return $encoded; 
        case JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded'; 
        case JSON_ERROR_STATE_MISMATCH: return 'Underflow or the modes mismatch'; 
        case JSON_ERROR_CTRL_CHAR: return 'Unexpected control character found'; 
        case JSON_ERROR_SYNTAX: return 'Syntax error, malformed JSON'; 
        case JSON_ERROR_UTF8: 
            $clean = utf8ize($value); 
            return safe_json_encode($clean, $options, $depth); 
        default: return 'Unknown error'; 

    } 
} 

function utf8ize($mixed) { 
    if (is_array($mixed)) { 
        foreach ($mixed as $key => $value) { 
            $mixed[$key] = utf8ize($value); 
        } 
    } else if (is_string ($mixed)) { 
        return utf8_encode($mixed); 
    } 
    return $mixed; 
} 

That you would use like this:

$data = curl_exec($ch);
$data = isafe_json_encode($data);
$data = json_decode($data, true);
curl_close($ch);

Useful links:

https://stackoverflow.com/questions/10199017/how-to-solve-json-error-utf8-error-in-php-json-decode

https://stackoverflow.com/questions/689185/json-decode-returns-null-after-webservice-call

  • his json is returning the desired value, as string, the problem is how it processes the received information. It tries to iterate the string without first converting to object/array.

  • @Mauroalexandre no Uro. In the comments of his reply he cited that the value returned is NULL. See there.

  • @Mauroalexandre the value returned from Decode is null! The string it is succeeding in rescuing. The problem is in converting.

  • solved with your help and Mauro see:

  • $data = array(); $data = curl_exec($ch); $data = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($data)); $data = json_decode($data, true); curl_close($ch); foreach($data as $key => $value){ &#echo "Name: {$value["Name"]} <br>"; }

  • @Rodrigopereiradefreitas do not forget to approve please

  • @Rodrigopereiradefreitas gave a job to make this answer.

  • Thank you very much. Too bad I can only approve 1 reply right. but Mauro’s reply was very helpful also thank you both

  • @Rodrigopereiradefreitas thanks! Hug!

  • kept my code only includes ( $data = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($data)); and ( $data = json_decode($data, true);) the rest the answer is the same Mauro but it was worth Andrei was of much help even.

  • Yes! I was right the @Mauroalexandre reply too, thanks to it you can identify the error of UTF8

  • @Rodrigopereiradefreitas tranquil! Hug!

Show 7 more comments

Browser other questions tagged

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