【问题标题】:PHP Fetch data from database and encode into JSON format Yii frameworkPHP 从数据库中获取数据并编码成 JSON 格式 Yii 框架
【发布时间】:2015-03-27 15:07:31
【问题描述】:

我在 yii 框架上有点挣扎。我想从我的 php 服务器连接到移动应用程序。在 yii 框架中如何进行 Json 编码并发送到移动应用程序?

【问题讨论】:

标签: php json yii encode


【解决方案1】:

Q:在yii框架下如何进行Json编码并发送到手机app?

答:

echo CJSON::encode($myArray);

问:如果我只想将用户名传递给移动应用程序,可以吗?我该怎么做?

答:

$criteria=new CDbCriteria;
$criteria->select='user_name';  // only select the 'user_name' column
$criteria->condition='user_id=:user_id';
$user_id = filter_input(INPUT_GET,'user_id');
if(FALSE===$user_id){
   header($_SERVER['SERVER_PROTOCOL'].' 404 not found');
   return false;
}

$criteria->params=array(':user_id'=>$user_id); // check 
$user=Users::model()->find($criteria); // $params is not needed

//echo json 写在答案#1

祝你好运!

【讨论】:

    【解决方案2】:

    Yii 的做法是

    echo CJSON::encode($myArray);
    

    底层代码使用 json_encode,但这里讨论了一些优点: Why use CJSON encode when we have json_encode

    【讨论】:

      【解决方案3】:

      我正在使用这个:

       public function actionGetUser($user_id)
              {   
                  header('Content-type: application/json');
                  $user = User::model()->findAll();
                  echo CJSON::encode($user);
                  Yii::app()->end();
           }   
      

      这在我测试时确实有效:localhost/myproject/index.php/user/getuser/user_id

      json 是否可以只编码一个属性并发送到移动应用程序?示例:有如下属性:user_id、user_name、user_email、user_photo

      如果我只想将 user_name 传递给移动应用程序,可以吗?我该怎么做?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多