Deserializing JSON in PHP

Asked

Viewed 96 times

3

Good afternoon, I’m having some doubts in PHP. I have a PHP file responsible only for presenting a CPF in JSON format, and with another file I am trying to consume this data to present on screen.

Consumption file Cpf.php presents the data in this way:

[{"id":"1","cpf":"098712321321","score":"400",]

I’m trying to do a foreach on this JSON to print the data but it’s giving an error.

Query file, serasaService.php:

    <html>

<head>
    <title>Api</title>
</head>

<body>
    <?php
    $json_file = file_get_contents("http://localhost/motora-proj/cpf.php");
    $json_str = json_decode($json_file, true);
    ?>
    <table>
        <thead>
            <tr>
                <?php
                foreach ($json_str as $e => $key) {
                    ?>
                    <th><?php echo $e; ?></th>
                <?php
                }
                ?>
            </tr>
        </thead>
        <tbody>
            <tr>
                <?php
                foreach ($json_str as $e => $key) {
                    ?>
                    <td><?php echo $key; ?></td>
                <?php
                }
                ?>
            </tr>
        </tbody>
    </table>
</body>
</html>

Error that is being displayed:

Warning: Invalid argument supplied for foreach() in /opt/lampp/htdocs/motora-proj/serasaService.php on line 17

Warning: Invalid argument supplied for foreach() in /opt/lampp/htdocs/motora-proj/serasaService.php on line 28

Can you help me please? Thank you!

2 answers

6

The format of this JSON is wrong, it should be like this:

{"id":"1","cpf":"09871204922","score":"400"}

as it is in the wrong shape, the json_decode is returning NULL, it is important to make an error handling before the foreach, how you are using php, you can use is_array() on a parole before the foreach

<html>
  <head>
    <title>Api</title>
  </head>
  <body>
    <?php
      $json_file  = file_get_contents( 'http://localhost/motora-proj/cpf.php' );
      $json_str   = json_decode( $json_file, true );
    ?>

    <?php if ( is_array( $json_str ) || is_object( $json_str ) ): ?>      
      <table>
        <thead>
          <tr>
          <?php foreach ( $json_str as $e => $key ): ?>          
            <th><?php echo $e; ?></th>
          <?php endforeach; ?>
          </tr>
        </thead>
        <tbody>
          <tr>
          <?php foreach ( $json_str as $e => $key ): ?>            
            <td><?php echo $key; ?></td>
          <?php endforeach; ?>
          </tr>
        </tbody>
      </table>
    <?php else: ?>
      <!-- mensagem de erro -->
    <?php endif ?>
</body>
</html>

5

Your JSON is poorly formed and are two possibilities of repair for it.

1 - [{"id":"1","cpf":"09871204922","score":"400"}]

2 - {"id":"1","cpf":"09871204922","score":"400"}

In the first case the JSON represents an array whose elements are objects. In the second case the JSON represents only one object.

A different approach is required for each case.

First case:

To answer I will simplify your code by removing the tags from HTML, keeping the code in PHP with a difference the JSON will be placed inline and printed:

<?php
    $json_file = '[{"id":"1","cpf":"09871204922","score":"400"}]';
    $json_str = json_decode($json_file, true);
    print_r($json_str);
?>

resulting in:

Array
(
    [0] => Array
        (
            [id] => 1
            [cpf] => 09871204922
            [score] => 400
        )

)

Meaning that decoded object is an array whose first element is also an array. In this case, iterate through the most external array to find the keys and values of the internal element:

<?php
    //Aumentado a complexidade do JSON
    $json_file = '[{"id":"1","cpf":"09871204922","score":"400"},{"id":"2","cpf":"09848269111","score":"250"}]';
    $json_str = json_decode($json_file, true);
    foreach($json_str as $item){
      foreach ($item as $key => $value) {
        echo $key . " ". $value . PHP_EOL;
      }
    }
?>

Which will result in:

id 1
cpf 09871204922
score 400
id 2
cpf 09848269111
score 250

Repairing your code for the first case:

<html>

<head>
    <title>Api</title>
</head>

<body>
    <?php
    $json_file = '[{"id":"1","cpf":"09871204922","score":"400"},{"id":"2","cpf":"09848269111","score":"250"}]';
    //file_get_contents("http://localhost/motora-proj/cpf.php");
    $json_str = json_decode($json_file, true);
    ?>
    <table>
        <thead>
            <tr>
                <?php
                  foreach ($json_str[0] as $e => $key) {
                    ?>
                    <th><?php echo $e; ?></th>
                <?php
                }
                ?>
            </tr>
        </thead>
        <tbody>
            <tr>
                <?php
                foreach($json_str as $item){
                  ?> <tr>
                <?php foreach ($item as $e => $key) {
                    ?>
                    <td><?php echo $key; ?></td>
                <?php
                }
                ?><tr><?php 
                }
                ?>
            </tr>
        </tbody>
    </table>
</body>
</html>

Will result in:

<html>

<head>
    <title>Api</title>
</head>

<body>
        <table>
        <thead>
            <tr>
                                    <th>id</th>
                                    <th>cpf</th>
                                    <th>score</th>
                            </tr>
        </thead>
        <tbody>
            <tr>
                 <tr>
                                    <td>1</td>
                                    <td>09871204922</td>
                                    <td>400</td>
                <tr> <tr>
                                    <td>2</td>
                                    <td>09848269111</td>
                                    <td>250</td>
                <tr>            </tr>
        </tbody>
    </table>
</body>
</html>

Second case:

In the second case JSON represents only one object being easier to iterate over its properties just by iterating directly over the object:

<?php 
    $json_file = '{"id":"1","cpf":"09871204922","score":"400"}';
    $json_str = json_decode($json_file, true);
    print_r($json_str);
?>

Resulting in:

Array
(
    [id] => 1
    [cpf] => 09871204922
    [score] => 400
)

Simply iterate directly on the object:

<?php 
    //Nesse caso não tem como aumentar a complexidade do objeto sem refatorar o código
    $json_file = '{"id":"1","cpf":"09871204922","score":"400"}';
    $json_str = json_decode($json_file, true);
    foreach ($json_str as $key => $value) {
      echo $key . " ". $value . PHP_EOL;
    }
?>

Result in:

id 1
cpf 09871204922
score 400

Making repair for that second case to question code:

<html>

<head>
    <title>Api</title>
</head>

<body>
    <?php
    $json_file = '{"id":"1","cpf":"09871204922","score":"400"}';
    //file_get_contents("http://localhost/motora-proj/cpf.php");
    $json_str = json_decode($json_file, true);
    ?>
    <table>
        <thead>
            <tr>
                <?php
                foreach ($json_str as $e => $key) {
                    ?>
                    <th><?php echo $e; ?></th>
                <?php
                }
                ?>
            </tr>
        </thead>
        <tbody>
            <tr>
                <?php
                foreach ($json_str as $e => $key) {
                    ?>
                    <td><?php echo $key; ?></td>
                <?php
                }
                ?>
            </tr>
        </tbody>
    </table>
</body>
</html>

Which will result in:

<html>

<head>
    <title>Api</title>
</head>

<body>
        <table>
        <thead>
            <tr>
                                    <th>id</th>
                                    <th>cpf</th>
                                    <th>score</th>
                            </tr>
        </thead>
        <tbody>
            <tr>
                                    <td>1</td>
                                    <td>09871204922</td>
                                    <td>400</td>
                            </tr>
        </tbody>
    </table>
</body>
</html>

Browser other questions tagged

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