alan
alan

Reputation: 33

access json from php class

I need to access a json $json_f from my class helper

<?php 
    class helper
    {
        protected $json_f = '{"fruits" : [
         {"id":0, "name":"Apple"},
         {"id":1, "name":"Orange"},
         {"id":2, "name":"Mango"}
       ]}';

     public function testc()
     {
        $data = json_decode($this->json_f);

        foreach ($data->fruits as $key) {
          echo '<p>';
          echo 'id : ' . htmlspecialchars($key->id) . '<br />';
          echo 'name : ' . htmlspecialchars($key->name) . '<br />';
          echo '</p>';
        }
     }
    }

?>

but im getting

this error: Trying to get property of non-object

below i have same in plain php

and which is working

<?php
$json_f = '{"fruits" : [
             {"id":0, "name":"Apple"},
             {"id":1, "name":"Orange"},
             {"id":2, "name":"Mango"}
         ]}';

$data = json_decode($json_f);

foreach ($data->fruits as $note) {
  echo '<p>';
  echo 'text : ' . htmlspecialchars($note->id) . '<br />';
  echo 'key : ' . htmlspecialchars($note->name) . '<br />';
}
?>

Upvotes: 0

Views: 51

Answers (2)

Alex Andrei
Alex Andrei

Reputation: 7283

Your json string is not valid.

Try this:

protected $json_f = '{"fruits" : [
     {"id":0, "name":"Apple"},
     {"id":1, "name":"Orange"},
     {"id":2, "name":"Mango"}
   ]}';

Note that I removed the commas after each fruit.

After this, running

$d = new helper();
$d->testc();

// outputs
// <p>id : 0<br />name : Apple<br /></p><p>id : 1<br />name : Orange<br /></p><p>id : 2<br />name : Mango<br /></p>

Everything should work out fine.

Upvotes: 3

Abhishek Sharma
Abhishek Sharma

Reputation: 6661

Try this code :-

Validate your json before use

 <?php 
        class helper
        {
           protected $json_f = '{"fruits" : [
         {"id":0, "name":"Apple"},
         {"id":1, "name":"Orange"},
         {"id":2, "name":"Mango"}
       ]}';

         public function testc()
         {
            $data = json_decode($this->json_f);
            foreach ($data->fruits as $key) {
              echo '<p>';
              echo 'id : ' . htmlspecialchars($key->id) . '<br />';
              echo 'name : ' . htmlspecialchars($key->name) . '<br />';
              echo '</p>';
            }
         }
        }
        $helper = new helper;
        $helper->testc();

    ?>

Run code

Upvotes: 1

Related Questions