dongsigan2044 2013-04-30 21: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 21: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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘