I am trying to extract all the comments from a Facebook account to my Webapp using Graph API by coverting the result into an array and then printing the array,but the result that I am getting is a blank array followed by the respective post.I don't know whats wrong.
if (isset($accessToken))
{
echo 'Posts:';
echo '<br>';
// getting all posts published by user
try {
$posts_request = $fb->get('/me/feed');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
$total_posts = array();
$posts_response = $posts_request->getGraphEdge();
$response_array = $posts_response->asArray();
if($fb->next($posts_response)) {
$total_posts = array_merge($total_posts, $response_array);
while ($posts_response = $fb->next($posts_response)) {
$response_array = $posts_response->asArray();
$total_posts = array_merge($total_posts, $response_array);
}
foreach ($total_posts as $key) {
if(isset($key['message'])){
echo $key['message'];
echo '<br>','<br>';
}
}
//print_r($total_posts);
} else {
$posts_response = $posts_request->getGraphEdge()->asArray();
foreach ($posts_response as $key) {
if(isset($key['message'])){
echo $key['message'];
echo '<br>','<br>';
$o_id= $key['id'];
echo $o_id;
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/113932879436074_129461837883178/comments',$accessToken);
}
catch(Facebook\Exceptions\FacebookResponseException $e)
{
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e)
{
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphEdge();
$comments=$graphNode->asArray();
print_r($comments);
}
Output:
113932879436074_131399157689446Array ( ) #TrueStory 😁
113932879436074_131393101023385Array ( ) Good afternoon Pihu Jaiswal
113932879436074_129461837883178Array ( ) Super bored
if($fb->next($posts_response)) {
$total_posts = array_merge($total_posts, $response_array);
while ($posts_response = $fb->next($posts_response)) {
$response_array = $posts_response->asArray();
$total_posts = array_merge($total_posts, $response_array);
}
foreach ($total_posts as $key) {
if(isset($key['message'])){
echo $key['message'];
echo '<br>','<br>';
}
}
//print_r($total_posts);
} else {
$posts_response = $posts_request->getGraphEdge()->asArray();
foreach ($posts_response as $key) {
if(isset($key['message'])){
echo $key['message'];
echo '<br>','<br>';
$o_id= $key['id'];
echo $o_id;
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('me?fields=id,name,posts{comments{message}}');
}
catch(Facebook\Exceptions\FacebookResponseException $e)
{
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e)
{
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
$comments=$graphNode->asArray();
print_r($comments);
}
Related
I'm working on a project to update a daatabase of products (price and stock) in prestashop based on data from a vending program. I'm doing this using PHP code and a MySQL conneectio to the DB.
The problem is that there is about 58.000 products and it seems to take very long to update all products.
Here is my code:
<?php
$host = '127.0.0.1';
$uname = '*******';
$pwd = '*******';
$db = "*******";
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
echo 'Updating init...' . "<br>";
//Create an instance of the class Update to get and update the data
$update = new Update();
try
{
// Get the product list from prestashop's DB
$productsFromPS = $update->getProductListFromPS($con);
// Cycle through all the product IDs
foreach ($productsFromPS as $product)
{
// Id of the product
$id = (int) $product['id_product'];
// Price from PS
$pricePS = (float) $product['price'];
// Get the product's stock from PS
$stockPS = $update->getProductStockFromPS($con, $id);
// Physical and reserved quantities in PS
$physQty = $stockPS['physical_quantity'];
$resQty = $stockPS['reserved_quantity'];
// Get product's price and stock from Vendus
$priceAndStockVendus = $update->getPriceAndStockFromVendus($id);
// Price from Vendus
$priceVendus = (float) $priceAndStockVendus[0];
// Tools for float compardsion
$zero = (float) 0.00;
$epsilon = (float) 0.00001;
// If the price in Vendus is 0, put 0 to stock in PS
if(!(abs($priceVendus-$zero) < $epsilon))
$stockVendus = (int) $priceAndStockVendus[1];
else
$stockVendus = 0;~
// If the prices do not match, update price
if(!(abs($pricePS-$priceVendus) < $epsilon))
$update->updatePrice($con, $id, $priceVendus);
// If the stocks do not matcth, update stock
if ($stockVendus!=$physQty)
$update->updateStock($con, $id, $stockVendus, $resQty);
}
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
/*
Class which method to get and update data
*/
class Update
{
public function getProductListFromPS ($con)
{
try
{
$sql_q = mysqli_query($con,"SELECT `id_product`, `price` FROM `ps_product` ORDER BY `id_product` ASC");
$output = "";
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
//echo $result['id_product'] . "<br>";
}
if($output)
{
//echo '4: ' . $output[4]['id_product'] . "<br>";
}
else
{
echo "empty ressult set <br>";
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "<br>";
}
return $output;
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage() . '<br>';
}
}
public function getProductStockFromPS ($con, $id)
{
try
{
$sql_q = mysqli_query($con,"SELECT `quantity`, `physical_quantity`, `reserved_quantity` FROM `ps_stock_available` WHERE `id_product` = $id");
$output = "";
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
//echo $result['id_product'] . "<br>";
}
if($output)
{
//echo 'qty: ' . $output[0]['quantity'] . "<br>";
//echo 'phys qty: ' . $output[0]['physical_quantity'] . "<br>";
//echo 'res qty: ' . $output[0]['reserved_quantity'] . "<br>";
}
else
{
echo "empty ressult set <br>";
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "<br>";
}
return $output[0];
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function getPriceAndStockFromVendus ($id)
{
try
{
$url = 'https://www.vendus.pt/ws/v1.1/products/';
$apiKey = '***********';
$method = 'GET';
$params = array(
'reference' => $id,
);
$url .= '?' . http_build_query($params);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $apiKey);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
//echo 'URL to Vendus - ' . $url . '<br />';
$result = curl_exec($curl);
$resultArray = json_decode($result, true);
curl_close($curl);
return array($resultArray[0]['gross_price'], $resultArray[0]['stock']);
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function updatePrice ($con, $id, $price)
{
try
{
$sql_q = mysqli_query($con,"UPDATE `ps_product` SET `price` = '$price' WHERE `id_product` = '$id'");
$sql_q = mysqli_query($con,"UPDATE `ps_product_shop` SET `price` = '$price' WHERE `id_product` = '$id' AND `id_shop` = '1'");
if($sql_q)
{
//echo $sql_q;
}
else
{
echo 'Invalid query: ' . mysqli_error($con) . "\n";
}
echo 'Price updated (' . $id . ')' . '<br />';
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function updateStock ($con, $id, $stock, $resQty)
{
try
{
$newPhysQty = $stock;
if ($newPhysQty!=0)
$newQty = $newPhysQty - $resQty;
else
$newQty = 0;
$sql_q = mysqli_query($con,"UPDATE `ps_stock_available` SET `physical_quantity` = '$newPhysQty', `quantity` = '$newQty' WHERE `id_product` = '$id'");
if($sql_q)
{
//echo $sql_q;
}
else
{
echo 'Invalid query: ' . mysqli_error($con) . "\n";
}
echo 'Stock updated(' . $id . ')' . '<br />';
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
}
}
?>
The plan is to have this code run at certain intervals to keep the DB updated.
Am I doing something wrong? Is there a faster way to do this?
This code is running on a server with 2GB of RAM and not a very fast processor. Should it be ruinning on a computer with higher specs?
I will appreciate any remarks/critcs about the code and tips on how to improve it.
Thanks in advance! ;)
EDIT: It appears running the code produces a 500 Internal Server Error, any idea what could be causing this? If I run the foreach only once it doesn't occur. How can i check the error in detail? I have CPannel as the control panel for the server.
i can't find the solution.
$prepStatement->execute(array_values($inv)); does not work
I got an error at this line.
my php script:
<?php
$response=array();
$json = $_REQUEST['json'];
$data = json_decode($json);
var_dump(json_decode($json, true));
print "Starting request". "<br/>";
if($_SERVER['REQUEST_METHOD'] == "POST" && (json_last_error() === JSON_ERROR_NONE))
{
if($data->connection && $data->wykazy)
{
print "connection and wykazy exist". "<br/>";
if ($data->connection->Host && $data->connection->db && $data->connection->User && $data->connection->password) {
print "connection Host, db, User, password are OK". "<br/>";
try
{
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbObj = new PDO('mysql:host='.$data->connection->Host.';dbname='.$data->connection->db, $data->connection->User, $data->connection->password, $opt);
print "Proba ustanowienia polaczenia! Bledy: " . $dbObj->errorCode() . "<br/>";
createWykaz($dbObj, $data);
}
catch (PDOException $e)
{
print "Blad podczas tworzeniu obiektu dbObj!: " . $e->getMessage() . "<br/>";
$response["success"]=0;
$response["message"]="Can not connect to database!: " . $e->getMessage();
echo json_encode($response);
die();
}
//$mysqli = new mysqli($data->connection->Host, $data->connection->User, $data->connection->password, $data->connection->db);
}
}
else
{
print "connection i wykazy nie istnieją! " . "<br/>";
$response["success"]=0;
$response["message"]="Error: Required fields are missing!";
echo json_encode($response);
}
}
function createWykaz($dbObj, $data)
{
try{
$allowedVariables = array(
'wyk_ilosc',
'wyk_czasod',
'wyk_czasdo',
'wyk_id_czynnosc',
'wyk_id_pracownik',
'wyk_id_partia',
'wyk_status',
);
$sql = "insert into wykaz (". implode(',', $allowedVariables) .")";
$sql.= " VALUES (". substr(str_repeat('?,', sizeof($allowedVariables)), 0, -1) .");";
print "sql: ". $sql . "<br/>";
if($prepStatement = $dbObj->prepare($sql)){
//edit
$dbObj->beginTransaction();
foreach ( $data->wykazy as $inv ) {
$res = $prepStatement->execute(array_values($inv));
}
/*
$prepStatement = $dbObj->prepare($sql)
foreach ($data->wykazy as $row) {
$dbObj->executeMultiple($prepStatement, $row);//return DB_OK
}
*/
$response["success"]=1;
$response["message"]="Wszystkie wykazy successfully added to Database!";
echo json_encode($response);
$dbObj->commit();
}
else {
$response["success"]=0;
$response["message"]="Błąd podczas przygotowania zapytania!"+ $prepStatement;
echo json_encode($response);
}
$dbObj=null;
$prepStatement=null;
}catch(PDOException $e){
//Error handling goes here
echo "Sorry, the website is experiencing problems.";
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $e->getMessage() . "\n";
$response["success"]=0;
$response["message"]="Our query failed to execute!". $e->getMessage();
echo json_encode($response);
$dbObj=null;
$prepStatement=null;
}
}
?>
it works till:
$prepStatement->execute(array_values($inv));
I am getting an error at this position, but $data->wykazy is an array.
I can change my code to:
$sth = $db->prepare('INSERT INTO numbers VALUES (?, ?, ?)');
foreach ($alldata as $row) {
$db->execute($sth, $row);
}
but I will try the other way.
Thanks for help
Sebastian
The output from Postman:
Postman part1
Postman part2
Using below code to get friend's list ,But its takes lot of time to give the result.How can I get the result quicker.Can anyone help me to solve this issue?
or is there any other way I can get friends list?
try {
$requestFriends = $fb->get('/me/taggable_friends?fields=name&limit=100');
$friends = $requestFriends->getGraphEdge();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// if have more friends than 100 as we defined the limit above on line no. 68
if ($fb->next($friends)) {
$allFriends = array();
$friendsArray = $friends->asArray();
$allFriends = array_merge($friendsArray, $allFriends);
while ($friends = $fb->next($friends)) {
$friendsArray = $friends->asArray();
$allFriends = array_merge($friendsArray, $allFriends);
}
foreach ($allFriends as $key) {
echo $key['name'] . "<br>";
}
} else {
$allFriends = $friends->asArray();
$totalFriends = count($allFriends);
$counter = 0;
foreach ($allFriends as $key) {
echo $key['name'] . "<br>";
$counter++;
}
echo $counter;
}
I have uploaded this code for solving facebook login problem. there're 3 files to implement this.. (login.php/playground_fb.php/member_index_fb.php) ... First you can find the simple button for href to playground_fb.php. and then there's some algorithm in playground_fb.php and then finally if user accept this app, then go to the member_index_fb.php with info sessions such as email address, first name, last name... I have searched a lot about these problems, but I only found the advice like input the session_start or stop the sessions or keep in 'www' like this... But it still remain unchanged... Who else help me please?
<!-- login.php -->
<div onclick="facebookLogin()" style="cursor: pointer;" align="center">
<img src="../build/img/login/login_facebook.png">
</div>
function facebookLogin() {
top.location.href = 'http://www.peeknchews.com/playground_fb.php';
}
<!-- playground_fb.php -->
<?php
session_start();
require_once('/home/kukkim/peeknchews.com/build/apis/facebook-php-sdk-v4/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => '257184091349723',
'app_secret' => '6c079349483a1bc959ce515df4e8138a',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getRedirectLoginHelper();
try {
if(isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
}
else {
$accessToken = $helper->getAccessToken();
}
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
//When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
//When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if(!isset($accessToken)) {
$permissions = ['email']; // optional
$loginUrl = $helper->getLoginUrl('http://'.$_SERVER['SERVER_NAME'].'/playground_fb.php', $permissions);
// die($_SESSION['FBRLH_' . 'state']);
echo "<script> top.location.href = '$loginUrl'; </script>";
// $permissions = ['email']; // optional
// $loginUrl = $helper->getLoginUrl('http://www.peeknchews.com/playground_fb.php', $permissions);
// echo 'LOG IN WITH FACEBOOK!';
}
else {
if(isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
else {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short lived access token for a long lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
try {
$response = $fb->get('/me?fields=email,first_name,last_name,name');
$userNode = $response->getGraphUser();
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returne d an error: ' . $e->getMessage();
unset($_SESSION['facebook_access_token']);
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returend an error: ' . $e->getMessage();
exit;
}
$fbId = $userNode->getId();
$fbEmail = $userNode->getProperty('email');
$fbName = $userNode->getName();
$fbFirstName = $userNode->getProperty('first_name');
$fbLastName = $userNode->getProperty('last_name');
$_SESSION['fbId'] = $fbId;
$_SESSION['fbEmail'] = $fbEmail;
$_SESSION['fbName'] = $fbName;
echo 'Name: ' . $fbName;
echo "<br>";
echo 'User ID: ' . $fbId . '<br>';
echo 'Email: ' . $fbEmail . '<br><br>';
echo 'Firstname : ' . $fbFirstName . '<br><br>';
echo 'Lastname : ' . $fbLastName . '<br><br>';
$image = 'https://graph.facebook.com/' . $fbId . '/picture?width=100';
echo "Picture<br><br>";
echo "<img src='$image' /><br><br> ";
//Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
echo "<script>top.location.href = 'http://www.peeknchews.com/member_index_fb.php';</script>";
}
?>
<!-- member_index_fb.php -->
<?php
session_start();
require_once('/home/kukkim/peeknchews.com/build/apis/facebook-php-sdk-v4/src/Facebook/autoload.php');
$sessionEmail=$_SESSION['user_email'];
//facebook
$fbSessionId = $_SESSION['fbId'];
$fbSessionEmail = $_SESSION['fbEmail'];
$fbSessionName = $_SESSION['fbName'];
require_once('/home/kukkim/peeknchews.com/config.php');
?>
<li>
<a class="nav-login fancybox fancybox.iframe" href="php_login/login.php"><img src="build/img/icons/login.png">
<?php
echo "<br>";
echo $fbSessionName . "<br>";
echo $fbSessionEmail . "<br>";
$image = 'https://graph.facebook.com/' . $fbSessionId . '/picture?width=100';
echo "<img src='$image' /><br><br> ";
?>
</a>
</li>
I am performing REST API GET call using PHP. Is there any easy way to browse $result and save its content to arrays.
<?php
$url = '...';
try
{
$result = file_get_contents( $url );
}
catch (Exception $e)
{
die('ERROR: ' . $e->getMessage());
}
var_dump($result);
?>
Here is an output (just some first lines):
string(7272)
"{"request":{"airport":{"requestedCode":"BCN","fsCode":"BCN"},"date":{"year":"2013","month":"7","day":"10","interpreted":"2013-07-10"},"hourOfDay":{"requested":"0","interpreted":0},"numHours":{"requested":"6","interpreted":6}
You should use json_decode
<?php
$url = '...';
try
{
$result = file_get_contents( $url );
$obj = json_decode($result);
}
catch (Exception $e)
{
die('ERROR: ' . $e->getMessage());
}
echo '<pre>';
var_dump($obj);
?>
OR
<?php
$url = '...';
try
{
$result = file_get_contents( $url );
$array = json_decode($result, true);
}
catch (Exception $e)
{
die('ERROR: ' . $e->getMessage());
}
echo '<pre>';
var_dump($arr);
?>