I'd like to display the number of likes for my Facebook page on my website. The previous method I used isn't working anymore since a couple of days.
When I call the Facebook graph API like this:
https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/549585444&format=json
It gives me the following output (fictional example):
[{"url":"http:\/\/www.facebook.com\/549585444","normalized_url":"http:\/\/www.facebook.com\/549585444","share_count":0,"like_count":122,"comment_count":0,"total_count":122,"click_count":0,"comments_fbid":null,"commentsbox_count":0}]
Now I like to echo the like count:
<?php
$fb_page = "549585444";
$url = "https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/".$fb_page."&format=json";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$json_returned = curl_exec($curl);
curl_close($curl);
$json_returned = json_decode($json_returned, true);
echo $json_returned['like_count'];
?>
But the number doesn't appear. Any idea why?
As you can see in the JSON output, the answer is wrapped in an array:
array(1) {
[0]=>
array(9) {
["url"]=>
string(33) "http://www.facebook.com/549585444"
["normalized_url"]=>
string(33) "http://www.facebook.com/549585444"
["share_count"]=>
int(0)
["like_count"]=>
int(0)
["comment_count"]=>
int(0)
["total_count"]=>
int(0)
["click_count"]=>
int(0)
["comments_fbid"]=>
NULL
["commentsbox_count"]=>
int(0)
}
}
To get the number output, you'll have to get the first item in the array by changing this row:
echo $json_returned['like_count'];
To this:
echo $json_returned[0]['like_count'];
Related
I'm using this little PHP function that I wrote to make calls to my master database:
$db_request = curl_init(DB_ROOT.'/action/register.php');
curl_setopt($db_request, CURLOPT_HEADER, 0);
curl_setopt($db_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($db_request, CURLOPT_POSTFIELDS, http_build_query($variables));
$db_response = curl_exec($db_request);
curl_close ($db_request);
parse_str($db_response, $information);
On register.php I use the following to respond:
echo http_build_query(array(
'test1'=>'value1',
'test2'=>'value2',
'test3'=>'value3'
));
My problem comes when trying to retrieve the first index of any given response. I can use var_dump($information) and will receive array(3) { ["test1"]=> string(6) "value1" ["test2"]=> string(6) "value2" ["test3"]=> string(6) "value3" }. However, when I try to echo $information['test1'], I receive this: Notice: Undefined index: test1 in....
Echoing anything other than the first index doesn't give me this problem.
Does anyone have any thoughts?
parse_str return type is void
Update your code
parse_str($db_response, $information);
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
This is the first time I have used curl, and am confused how exactly the $response is formatted, and how I go about accessing the information I want in it. I am trying to access a particular variable from a curl response in PHP to be used in a future conditional. I was provided the URL, and headers to use as an API endpoint, and thus can't change anything on that end. Here is the code for the curl response :
$ch = curl_init();
$url = "https://thewebsitesurl.com";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'x-branch: 21',
'x-branchhash: fijef89ivjw8934y8f9fifk920a',
'accept: application/json'
));
$response = curl_exec($ch);`
The contents of a var_dump($response) yields :
string(187) "{"code":"5122","time":"1589812650","voucher":{"code":"5122","comments":"","amount":"11.00","balance":"11.00","created":"1589609333","expiry":"1652616000","redeemed":false,"voided":false}}"
I need to access the "redeemed" and "voided" field. Of course this being a big long string means I can't do that (I believe). Is there a CURLOPT I should be setting so the response isn't received as one big string?
Further if I decode it with $data = var_dump(json_decode($result, true)); the contents are :
array(3) { ["code"]=> string(4) "5122" ["time"]=> string(10) "1589814039" ["voucher"]=> array(8) { ["code"]=> string(4) "5122" ["comments"]=> string(0) "" ["amount"]=> string(5) "11.00" ["balance"]=> string(5) "11.00" ["created"]=> string(10) "1589609333" ["expiry"]=> string(10) "1652616000" ["redeemed"]=> bool(false) ["voided"]=> bool(false) } }
To me this seems much more workable than a long string. However I am struggling to access the ["expiry"], ["redeemed'], and ["voided"] variables. In fact I am struggling just to access the ["code"] string "5122" I have tried :
echo $data[0]['code'];
echo $data[0]["code"];
echo $data['code'];
echo $data["code"];
All 4 of those echos are blank. I have tried to remove "curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);" as well. Afterwards var_dump($result); looks like :
{"code":"5122","time":"1589815247","voucher":{"code":"5122","comments":"","amount":"11.00","balance":"11.00","created":"1589609333","expiry":"1652616000","redeemed":false,"voided":false}}bool(true)
I am probably misunderstanding something basic here. But any help would be appreciated on how I could access the values in ["expiry"], ["redeemed'], and ["voided"]. Thank you for your assistance.
$data = json_decode($result, true);
This will return an array
$data = json_decode($result);
This will return an object.
Do not use var_dump inside this because it is a parse function, just for dumping data. So the final should be:
$data = json_decode($result, true);
$code = $data['code']; // " or ' are not different in this case
I am following this part of the documentation: http://developers.marketo.com/rest-api/assets/tokens/ and I always get the following an error: Fields cannot be empty.
Have anyone make it worked?
public function create_token($folder_id,$name,$content,$folder_type = 'Program')
{
$folder_id = intval($folder_id);
$endpoint = 'rest/asset/v1/folder/'.$folder_id.'/tokens';
$body = new stdClass();
$body->folderType = $folder_type;
$body->name = $name;
$body->type = 'rich text';
$body->value = $content;
$body_encoded = json_encode($body);
echo $url = $this->url . $endpoint . ".json?access_token=" . self::$token;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_encoded);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
The reason for the Content-Type header was a suggestion from Marketo: https://www.screencast.com/t/CL5ZtPo1o
This is the answer from the request I keep getting:
object(stdClass)#1934 (4) {
["success"]=>
bool(false)
["warnings"]=>
array(0) {
}
["errors"]=>
array(4) {
[0]=>
object(stdClass)#1935 (2) {
["message"]=>
string(20) "name cannot be null."
["code"]=>
string(3) "701"
}
[1]=>
object(stdClass)#1936 (2) {
["message"]=>
string(20) "type cannot be null."
["code"]=>
string(3) "701"
}
[2]=>
object(stdClass)#1937 (2) {
["message"]=>
string(101) "Token type is either null, blank or invalid. Please refer to the documentation for valid token types."
["code"]=>
string(3) "701"
}
[3]=>
object(stdClass)#1938 (2) {
["message"]=>
string(21) "value cannot be null."
["code"]=>
string(3) "701"
}
}
["requestId"]=>
string(16) "11d1#15b49284636"
}
You don't have to post token fields as JSON object: json_encode($body)
Fields are passed as request parameters or as a regular form
This request with works well for me:
POST https://123-FOO-456.mktorest.com/rest/asset/v1/folder/1039/tokens.json?value=TestTokenValue&folderType=Program&name=TestToken&type=text
In this case, you also don't have to specify content type Content-Type: x-www-form-urlencoded
I'm not PHP dev, but you can look here for examples how to post form data - PHP + curl, HTTP POST sample code?
actually I'm working on coding an API for my business, I have an issue on my code and I couldn't figure out the problem, here is the class:
<?php
class ApiCaller
{
//some variables for the object
private $_app_id;
private $_app_key;
private $_api_url;
//construct an ApiCaller object, taking an
//APP ID, APP KEY and API URL parameter
public function __construct($app_id, $app_key, $api_url)
{
$this->_app_id = $app_id;
$this->_app_key = $app_key;
$this->_api_url = $api_url;
}
//send the request to the API server
//also encrypts the request, then checks
//if the results are valid
public function sendRequest($request_params)
{
//encrypt the request parameters
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->_app_key, json_encode($request_params), MCRYPT_MODE_ECB));
//create the params array, which will
//be the POST parameters
$params = array();
$params['enc_request'] = $enc_request;
$params['app_id'] = $this->_app_id;
//initialize and setup the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$result = curl_exec($ch);
//json_decode the result
$result = #json_decode($result);
//check if we're able to json_decode the result correctly
if( $result == false || isset($result->success) == false ) {
throw new Exception('Request was not correct');
}
//if there was an error in the request, throw an exception
if( $result->success == false ) {
throw new Exception($result->errormsg);
}
//if everything went great, return the data
return $result->data;
}
}
The problem that there is no data returned from the sendRequest function, just throw 'Request was not correct' exception, I tried to test the code but with no luck. I'm using xampp-win32-5.6.8-0-VC11 and I have curl-7.43.0-win64 installed,,,
Any help will be appreciated and thanks.
Edit:
I use this code to test the function and it worked:
<?php
$_app_key = '28e336ac6c9423d946ba02d19c6a2632';
$_api_url = 'http://localhost/myAPI/simpletodo_api/';
$_app_id = 'APP001';
$params = array(
'controller' => 'todo',
'action' => 'read',
'username' => 'nikko',
'userpass' =>'test1234'
);
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $_app_key, json_encode($params), MCRYPT_MODE_ECB));
$pa = array();
$pa['enc_request'] = $enc_request;
$pa['app_id'] = $_app_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pa);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$errorNo = curl_errno ($ch );
$result = #json_decode($result);
var_dump($result);
and the result:
"object(stdClass)#1 (2) { ["data"]=> array(2) { [0]=> object(stdClass)#2 (5) { ["todo_id"]=> string(10) "1323343689" ["title"]=> string(10) "test title" ["description"]=> string(28) "test description weee wasted" ["due_date"]=> string(10) "12/02/2011" ["is_done"]=> string(4) "true" } [1]=> object(stdClass)#3 (5) { ["todo_id"]=> string(10) "1323429521" ["title"]=> string(3) "wee" ["description"]=> string(11) "adsa wasada" ["due_date"]=> string(10) "12/21/2011" ["is_done"]=> string(4) "true" } } ["success"]=> bool(true) }"
So where is the problem then??
Be carefull with the following line :
$result = #json_decode($result);
You are hiding any error message by using the #.
I would suspect you are not receiving a valid json response and then $result would be set to false, because json_decode would not work.
So what happens if you not getting a valid json back? Your code should handle that error case.
In order to debug, try to add var_dump($result); just after the curl_exec call, that should help you understand what's wrong.
As stated in the comments you should check the curl error codes
$errorNo = curl_errno ($ch );
http://php.net/manual/en/function.curl-errno.php
In the case of a 404 or other error you have no way to know in your code as formatted.
I'm building a script to verify a transaction receipt with Apple's itunesconnect site (iphone dev) and I can't figure out where's the error in my code. I want to get the "status" value.
Please help me to find what am I doing wrong:
<?php
include("config.php");
$receipt = json_encode(array("receipt-data" => $_GET["receipt"]));
$response_json = do_post_request($url, $receipt);
$response = json_decode($response_json);
//Here's where I try to get the "status" key but doesn't work
echo $response['status'];
//echo $response->status;
function do_post_request($url, $data)
{
//initialize cURL
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
// howmany parameter to post
curl_setopt($ch, CURLOPT_POST, 1);
// the receipt as parameter
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result= curl_exec ($ch);
curl_close ($ch);
return $result;
}
?>
and the answer to the iPhone looks like:
{"receipt":{"item_id":"327931059", "original_transaction_id":"1000000000074412", "bvrs":"1.0", "product_id":"sandy_01", "purchase_date":"2009-09-29 16:12:46 Etc/GMT", "quantity":"1", "bid":"com.latin3g.chicasexy1", "original_purchase_date":"2009-09-29 16:12:46 Etc/GMT", "transaction_id":"1000000000074412"}, "status":0}
but only "status":0 matters for now
- Thank's
From the manual on json_decode()
Returns an object or if the optional
assoc parameter is TRUE, an
associative array is instead returned.
NULL is returned if the json cannot
be decoded or if the encoded data is
deeper than the recursion limit.
So either send TRUE for the 2nd parameter
$response = json_decode($response_json, true);
Or access the decoded JSON with object syntax
$response->status;
EDIT
Isolated test
$json = <<<JSON
{"receipt":{"item_id":"327931059", "original_transaction_id":"1000000000074412", "bvrs":"1.0", "product_id":"sandy_01", "purchase_date":"2009-09-29 16:12:46 Etc/GMT", "quantity":"1", "bid":"com.latin3g.chicasexy1", "original_purchase_date":"2009-09-29 16:12:46 Etc/GMT", "transaction_id":"1000000000074412"}, "status":0}
JSON;
$response = json_decode( $json );
echo $response->status;
$response2 = json_decode( $json, true );
echo $response2['status'];
Output is
00
You should be able to use:
$response->status;
Passing an optional param of true to the json_decode function will bring the results back as an associative array.
Have you checked your response_json variable to check that the data is being deserialised correctly? i.e:
var_dump($response);
Which should yield:
object(stdClass)#1 (2) {
["receipt"]=>
object(stdClass)#2 (9) {
["item_id"]=>
string(9) "327931059"
["original_transaction_id"]=>
string(16) "1000000000074412"
["bvrs"]=>
string(3) "1.0"
["product_id"]=>
string(8) "sandy_01"
["purchase_date"]=>
string(27) "2009-09-29 16:12:46 Etc/GMT"
["quantity"]=>
string(1) "1"
["bid"]=>
string(22) "com.latin3g.chicasexy1"
["original_purchase_date"]=>
string(27) "2009-09-29 16:12:46 Etc/GMT"
["transaction_id"]=>
string(16) "1000000000074412"
}
["status"]=>
int(0)
}