Reputation: 323
I'm new to php. I'm trying to write a simple plugin that calls the api and returns a JSON response.
When I write the same code outside function, I get a JSON response. But the issue is when I use the function below, it doesn't return any value.. The page seems blank
Here is my function
function getDOTD(){
try{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $baseUrl."offers/v1/dotd/json");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Fk-Affiliate-Id:'.get_option('affiliate_id'),'Fk-Affiliate-Token:'.get_option('affiliate_token')));
$result = curl_exec($curl);
curl_close($curl);
print($result);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n"; abort;
}
}
i have also tried to use return instead of print() but that too didn't worked. this is how i call my function -
print(getDOTD());
Any help appreciated... TIA :)
Upvotes: 0
Views: 286
Reputation: 1429
You need to know how the variables scope works.
From the PHP Documentation
<?php
$a = 1; /* global scope */
function test(){
echo 'local variable: ' . $a; /* reference to local scope variable // NULL */
}
test();
?>
To be able to access to the global scope you need to use the global
keyword inside your function
<?php
$a = 'Hello World'; /* global scope */
function test(){
global $a;
echo 'global variable: ' . $a; /* reference to global scope variable // Hello World */
}
test();
?>
More info about the variables scope
Upvotes: 1