I’m trying to integrate a third-party API (used for interacting with the OpenSecrets.org data) into my Codeigniter site, and keeping getting an error about an object being treated as a string even though the variable is an array.
The original api is available here: https://github.com/bpilkerton/php-crpapi/blob/master/crpapi.php.
My modifications are available here: http://pastebin.com/HmZyhQJR.
I’ve modified the class so that the filename and class declaration match and both have initial capital letters, and I’ve modified the constructor so that it only accepts one array of parameters, which are set when the class is called from my controller.
The pertinent section of my modified code is below. I get errors for the first line of the private function loadParams and the foreach loop in that function. The first error is:
Object of class stdClass could not be converted to string
And the second is:
Invalid argument supplied for foreach()
Custom class:
class Crp {
function __construct($params) {
$this->apikey = "a04a90aa18e9e482b3ff2318d313db53";
$this->baseurl = "http://api.opensecrets.org/";
$this->output = "json";
//Allow output type to be overridden on object instantiation
$this->output = isset($params['output']) ? $params['output']: $this->output;
$this->method = $params['method'];
self::loadParams($params);
/*$this->fileHash = md5($method . "," . implode(",",$params));
$this->cacheHash = "dataCache/" . $this->fileHash;
$this->cacheTime = 86400; #one day*/
}
private function loadParams($params) {
$this->url = $this->baseurl . "?method=" . $this->method .
"&apikey=" . $this->apikey;
foreach ($params as $key=>$val) {
$this->url .= "&" . $key . "=" . $val;
$this->$key = $val;
}
return;
}
And the call in the Controller
$crp_id = $this->_getRefId($id,'indiv','crp');
$this->load->library('crp',array("method" => "candContrib","cid"=> $crp_id,"cycle"=>"2010","output"=>"json"));
// grabs the CRP id from my reference table; have tested and correctly returns string
function _getRefId($id,$type,$src)
{
switch ($src) {
case 'crp':
$field = 'ref_id as id';
break;
}
switch ($type) {
case 'indiv':
$this->db->select($field);
$this->db->where('ref_id',$id);
$query = $this->db->get('my_ref_table');
if($query->num_rows() > 0)
{
$query = $query->row();
return $query->id;
}
break;
case 'org':
break;
}
}
From the way I understand creating custom libraries in CI, this is how I pass an array of parameters to the new instantiation, and it only accepts one array. Any thoughts?
Seems to work fine in my setup. Could you possibly be using an object for $crp_id? Can you post the code for the controller as well?
EDIT: I plugged in a stdClass object for $crp_id and got your exact same first error.
EDIT: