Print the result of the REST API GET call - php

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);
?>

Related

Updating price and stock of thousands of entries in DB

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.

How to extract comments from a Facebook account to my Webapp?

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);
}

Facebook-PHP-SDK Getting friends list is very slow

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;
}

How to echo query results from Parse.com in table form? Parse PHP SDK

I'm trying to retrieve this class from Parse.com and show it in a table form in a php website. It will be very helpful if someone can show me an example of how it's done. With little html and php knowledge, everything has been so confusing.
<?php
include('parsekey.php');
use Parse\ParseQuery;
try{
$query = new ParseQuery("Stock");
$query->select("Stock");
$results = $query->find();
echo "RESULT: ";
print_r($results);
echo "Successfully retrieved " . count($results) . " data.";
}
catch (Exception $e){
echo $e->getMessage();
}
?>
Simple.... just loop them.
try{
$query = new ParseQuery("Stock");
$query->select("Stock");
$results = $query->find();
foreach($results as $result){$column_value = $result->get('column_name');}
echo "Successfully retrieved " . count($results) . " data.";
}
catch (Exception $e){
echo $e->getMessage();
}
?>

This is causing my page to load very slow or not at all?

I just updated from php 5.3.4 to 5.3.8. After the update it seems that all my code that includes try{ causes my page to hang and use up all my server memory.
if(preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip)){
$xml = #file_get_contents('http://' . $this->service . '/' . $this->version . '/' . $name . '/?key=' . $this->apiKey . '&ip=' . $ip . '&format=xml');
try{
$response = #new SimpleXMLElement($xml);
foreach($response as $field=>$value){
$result[(string)$field] = (string)$value; }
return $result;
}
catch(Exception $e){ $this->errors[] = $e->getMessage();
return;
}
}
This also causes a major issues
<?php
try{
$gt = new Gtranslate;
$gt->setRequestType('curl');
$SQL = "SELECT * FROM PAGE_CONTENT WHERE live_page = '1'";
$result = mysql_query( $SQL );
while( $row = mysql_fetch_array( $result ) ) {
$page_id_sub = $row["page_id"];
$page_title = $row["page_title"];
$page_permalink = $row["page_permalink"];
if(empty($mylang)){
echo "<a href='/$permalink/$page_permalink.html'>$page_title</a> |";
}
else {
$page_trans = $gt->$mylang("$page_title");
echo "<a href='/$permalink/$page_permalink.html'>$page_trans</a> |";
}
}
}
catch (GTranslateException $ge){
echo $ge->getMessage();
}
?>
This probably has very little to do with try and much more to do with your remote requests (i.e. file_get_contents() and $gt->$mylang()).
As a benchmark, remove those lines and see how your page performs. If they are indeed the culprit, you may want to consider caching their response or some other approach so your not making the request on every page load.

Categories