Help me with a foreach array php

2

Good afternoon,

I'm using PHP's cURL to get a json from an api. Data is being stored correctly in a variable. But when I try to display the data with a foreach of the error in the line where the foreach is:

The json that comes from the site looks 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:

  

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? Thank you in advance

    
asked by anonymous 29.05.2018 / 18:53

2 answers

1

Your json can return NULL for several reasons:

I'll 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 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 it is, there are a few 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; 
} 

What would you use like this:

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

Useful links:

p>

link

    
29.05.2018 / 21:45
2

Being brief, PHP does not recognize the content of $data as an object, nor as an array (referenced in the foreach), so you need to convert the received string 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>";


}

This way you can iterate the object, as much as an array. You can use var_dump() before foreach to see the contents and type of $data , so it's easier to find the problem.

    
29.05.2018 / 19:00