dongsigan2044 2013-04-30 13:43
浏览 64
已采纳

CodeIgniter视图中未定义的JSON变量

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>

展开全部

  • 写回答

1条回答 默认 最新

  • dqyknf4423 2013-04-30 13:46
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了