Reputation: 61
I am trying to pull a JSON object from another page and then break it into pieces and values to my php document's variables and populate the page with them.
The issue I am running into is that while the curl_exec call prints the JSON object, I cannot do anything to it from that point on. Below is my code:
$json_url = "localhost:8080/query";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $json_url);
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
$result = json_decode(curl_exec($ch));
var_dump ($result);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
// ON SUCCESS
$json_a = $result[10];
var_dump ($json_a);
Here is a sample of a piece of the result:
["4"]=> array(2) { [0]=> int(1325003843) [1]=> array(2) { [0]=> int(47) [1]=> array(17) { [0]=> array(2) { [0]=> int(0) [1]=> int(1) } [1]=> array(2) { [0]=> int(17) [1]=> int(44) } [2]=> array(2) { [0]=> int(3) [1]=> int(4) } [3]=> array(2) { [0]=> int(3) [1]=> int(4) } [4]=> array(2) { [0]=> int(3) [1]=> int(4) } [5]=> array(2) { [0]=> int(3) [1]=> int(4) } [6]=> array(2) { [0]=> int(3) [1]=> int(4) } [7]=> array(2) { [0]=> int(3) [1]=> int(4) } [8]=> array(2) { [0]=> int(3) [1]=> int(4) } [9]=> array(2) { [0]=> int(3) [1]=> int(4) } [10]=> array(2) { [0]=> int(3) [1]=> int(4) } [11]=> array(2) { [0]=> int(3) [1]=> int(4) } [12]=> array(2) { [0]=> int(3) [1]=> int(4) } [13]=> array(2) { [0]=> int(2) [1]=> int(3) } [14]=> array(2) { [0]=> int(2) [1]=> int(3) } [15]=> array(2) { [0]=> int(2) [1]=> int(3) } [16]=> array(2) { [0]=> int(2) [1]=> int(3) } } } }
The var_dump ($result); returns int(1) and the other var_dump returns NULL. The curl_exec actually prints the JSON object, so I know tat it is at least grabbing it. Thanks so much for any help you might offer!
Upvotes: 1
Views: 896
Reputation: 3848
You could also just do something like
$json_url = "localhost:8080/query";
// $protocol should be the protocol used, ie. 'ftp://', 'http://' or 'https://'
// to produce an URL like 'ftp://user:pass@localhost:8080/query'
$result = file_get_contents($protocol . $user.":".urlencode($pass) . '@' . $json_url);
if($result !== false) { // ON SUCCESS
$result = json_decode($result, true);
var_dump ($result);
if(isset($result[10])) { // If index 10 of $result exists
$json_a = $result[10];
var_dump ($json_a);
}
} else {
// error occured
}
Upvotes: 1
Reputation: 8980
With CURLOPT_RETURNTRANSFER set to false, curl_exec returns only true or false. Set CURLOPT_RETURNTRANSFER to true and curl_exec should return the result for you.
Upvotes: 3