1

Why am I getting the following errors

A PHP Error was encountered Severity: Warning Message: Undefined variable: json Filename: views/search_page.php Line Number: 8

A PHP Error was encountered Severity: Warning Message: Trying to get property of non-object Filename: views/search_page.php Line Number: 8

A PHP Error was encountered Severity: Warning Message: Invalid argument supplied for foreach() Filename: views/search_page.php Line Number: 8

with this code?

search.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Search extends CI_Controller {

    public function index()
    {

        $json = json_decode(file_get_contents('http://search.twitter.com/search.json?q=to%3astackexchange'));

        $this->load->view('search_page', $json);
    }
}

/* End of file search.php */
/* Location: ./application/controllers/search.php */

search_page.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Twitter Test</title> 
</head>
<body>
<?php foreach ($json->results as $result): ?>
    <h2><?php echo $result->from_user; ?></h2>
<?php endforeach ?>
</body>
</html>
6
  • 1
    JSON doesn't have variables. Commented Apr 30, 2013 at 21:45
  • 1
    @Madbreaks: The title is "Undefined JSON variable in CodeIgniter View" JSON doesn't have variables. But the question seems to be about a PHP variable called $json, so perhaps "Undefined PHP variable json ..." Commented Apr 30, 2013 at 21:47
  • 1
    @T.J.Crowder Pedantic for the sake of being so. The question made it clear what op was asking. Commented Apr 30, 2013 at 21:55
  • 1
    @Madbreaks: Actually, no. Perhaps consider not rushing to judge people you don't know in favor of giving them the benefit of the doubt. Capitalization matters, and people see the title in views in which they don't see the question, and the question is (actually, was -- I've corrected it) tagged json, which (upon close reading) is completely irrelevant. Commented Apr 30, 2013 at 22:03
  • 1
    @T.J.Crowder Valid points. I agree that without the context it would/could be confusing, and json was definitely not an appropriate tag. Thanks for clarifying. Commented Apr 30, 2013 at 22:13

1 Answer 1

4

You need to assign the variable you're passing in ($json) to a name ("json")

$this->load->view('search_page', array('json' => $json));

Perhaps a more clear example:

$this->load->view('search_page', array('myNeatObject' => $json));

// ...then, in your view, you could

<p>This is the JSON: <?php echo print_r($myNeatObject, true) ?></p>

That's how you name a variable for access in a view.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.