从API密钥获取数据以保存到数据库中

时间:2017-03-05 18:37:28

标签: json codeigniter api

我正在使用Codeigniter制作的网站应用程序。我想从API密钥中获取数据并将其保存到数据库中。我有一个基本代码,但它不起作用。我需要哪些文件?我是新手,在这项任务上遇到了很多困难。

控制器:

  getTestBed().get(YourService)

型号:

public function ee_cron_job(){

  $decode_data = $this->Campaign_model->get_ee_api();
  $this->db->query($query);
  foreach ($decode_data->result() as $current) {
    $data = array(
          'ee_name' => $current['Name'],
          'ee_clicked' => $current['Clickedcount'],
          'ee_open' => $current['Openedcount'] ,
          'ee_recipient' => $current['Recipientcount'],
          'ee_sent' => $current['Sentcount'],
          'ee_failed' => $current['Failedcount'],
          'ee_unsubscribe' => $current['Unsubscribedcount'],
          'ee_dateedded' => $current['Dateadded'],
          'ee_lastactive' => $current['Lastactivity']
    );
  $this->db->query($query);
  $this->Campaign_model->add($data);
  $this->db->update('ee_campaigns');

 }
} 

首先,错误是: 致命错误:允许的内存大小为134217728字节耗尽(尝试分配5085070 比我添加了ini_set('memory_limit','1024M');并发生第二个错误: 致命错误:超过最长执行时间120秒。

我该怎么做才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

嗯,你把你的模型放在一个永无止境的循环中。

public function get_ee_api() {

  $response = Requests::get("https://api.elasticemail.com/v2/campaign/list?apikey=*", array());
  //$this->get_ee_api(); take this line off. The function is calling it self over and over.
  return json_decode($response->body, true);

}

这应该会让你摆脱执行时间问题,并希望你也能解决内存问题。

如果您需要遵循MVC模式,则需要停止在控制器中执行数据库操作。 获取模型以执行查询并将结果传递回控制器。 循环结果,我也没有在控制器中看到查询变量。

- 尝试使用curl

public function get_ee_api() {
    $response = $this->get_web_page("https://api.elasticemail.com/v2/campaign/list?apikey=*");
    $resArr = array();
    $resArr = json_decode($response);
    echo "<pre>"; print_r($resArr); echo "</pre>";

    //return json_decode($resArr); remove comments if you get proper output

    }


    private function get_web_page($url) {
       $options = array(
            CURLOPT_RETURNTRANSFER => true,   // return web page
            CURLOPT_HEADER         => false,  // don't return headers
            CURLOPT_FOLLOWLOCATION => true,   // follow redirects
            CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
            CURLOPT_ENCODING       => "",     // handle compressed
            CURLOPT_USERAGENT      => "test", // name of client
            CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
            CURLOPT_TIMEOUT        => 120,    // time-out on response
        ); 

        $ch = curl_init($url);
        curl_setopt_array($ch, $options);

        $content  = curl_exec($ch);

        curl_close($ch);

        return $content;
    }
相关问题