7
votes

I'm trying to print my key/value pairs of data in my CodeIgniter view. However, I'm getting the following error. What I'm I doing wrong?

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/search_page2.php

Line Number: 8

application/controller/search.php

// ...
        $this->load->library('/twitter/TwitterAPIExchange', $settings);
        $url = 'https://api.twitter.com/1.1/followers/ids.json';
        $getfield = '?username=johndoe';
        $requestMethod = 'GET';     
        $twitter = new TwitterAPIExchange($settings);

        $data['url'] = $url;
        $data['getfield'] = $getfield;
        $data['requestMethod'] = $requestMethod;        

        $this->load->view('search_page2', $data);
// ...

application/views/search_page2.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Twitter Test</title> 
</head>
<body>
<?php print_r($data); ?>

<?php foreach ($data as $key => $value): ?>
    <h2><?php echo $key . ' ' . $value . '<br />'; ?></h2>
<?php endforeach ?>
</body>
</html>
2

2 Answers

5
votes

to get the data array accessible in the view do like

    $data['url'] = $url;
    $data['getfield'] = $getfield;
    $data['requestMethod'] = $requestMethod;        
    
    $data['data'] = $data;
    $this->load->view('search_page2', $data);

else only the variables with names as its keys will be available in the view not the data variable we pass.

update:

this is in response to your comment to juan's answer Actually if you are trying make it working in the other way proposed.

controller code will be having no change from the code you posted.

    $data['url'] = $url;
    $data['getfield'] = $getfield;
    $data['requestMethod'] = $requestMethod;
    $this->load->view('search_page2', $data);

but in the view code you will need to just do.

 <h2>url <?PHP echo $url; ?><br /></h2>
 <h2>getfield <?PHP echo $getfield; ?><br /></h2>
 <h2>requestMethod <?PHP echo $requestMethod; ?><br /></h2>

instead of the foreach loop as your keys in $data are already available as respective named variables inside the view.

4
votes

The variables to use in your template are

 $url, $getfield, $requestMethod

$data is the container for the variables that are passed to the view and not accessible directly

If you do need $data accessible to the view, use a different wrapper object

 $container  = array();
 $container  ['url'] = $url;
 $container  ['getfield'] = $getfield;
 $container  ['requestMethod'] = $requestMethod;
 $container  ['data'] = $data;
 $this->load->view('search_page2', $container);