I am working on facebook pagination, I have searched but didn't get relevant answer.
First I am fetching 10 result and after that onclick function I want to fetch next 10 results for this I am passing -
[paging] =>
Array
(
[previous] => https://graph.facebook.com/v2.9/....D&__previous=1
[next] => https://graph.facebook.com/........
)
as parameter,I also tried passing next URL as parameter but still it is not working, if I pass $feedEdge as associated I am getting response as null,below is my code
$response = self::$_FBINSTANCE->get('/me/feed?fields=id,message&limit=' . $_pagination->limit);
if(empty($_nextFeed)){
$feedEdge = $response->getGraphEdge();
$nextFeed = $response->getGraphEdge()->getMetaData();
}else{
$feedEdge=$response->next($_nextFeed);
$nextFeed = $response->getGraphEdge()->getMetaData();
}
$result = array();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
return array(
'result' => $result,
'totalRows' => $totalCount,
'nextFeed' => $nextFeed
);
using v2.9 version, what parameter I should pass for $response->next(); help me if I am wrong .
I found solution for this question...
If any one is trying for same try below code.
$result = array();
if(empty($_nextFeed)){
$response = $fb->get('/me/feed?fields=id,message&limit=' . $_pagination->limit);
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
$nextFeed = $response->getGraphEdge()->getMetaData();
}else{
//to get until time stamp form next url
$nextURl=parse_url($_nextFeed['paging']['next']);
parse_str($nextURl['query'], $URL);
$response = $fb->get('/me/feed?fields=id,message&limit='.(($_pagination->limit)+1).'&until='.$URL['until']);
$feedEdge = $response->getGraphEdge();
foreach ($feedEdge as $status) {
$result[] = $status->asArray();
}
//because result repeats last array of previous request
array_splice($result,0,1);
$nextFeed = $response->getGraphEdge()->getMetaData();
}
return array(
'result' => $result,
'totalRows' => $totalCount,
'nextFeed' => $nextFeed
);
It works :)
Related
I am trying to make a code verifier with the following code. I've looked at the answers in StackOverflow but couldn't get the right result.
The code is working fine but I want to echo just two value.
validate.php page code is here:
if(isset($apKey) && isset($code)) {
$en = new En();
$Key = $apKey;
$Codes = $code;
if($Key == null || $Codes == null) {
echo json_encode(['data' => 'No Key or code found, Please try again']);
exit;
}
$response = $en->validate($Key,$Codes);
$result = json_decode($response);
$elements = json_encode(['data' => $result]);
echo $elements;
exit;
}
echo json_encode(['data' => 'No Key or code found, Please try again']);
exit;
Now I am trying to check this validate page results using this code:
$siteurl = urlencode($_SERVER['SERVER_NAME']);
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false
)
);
$file = file_get_contents('http://www.validates.com/validate.php?code=' . $check , false, stream_context_create($arrContextOptions));
$checks = json_decode($file, true);
$elements = $checks['data'];
echo print_r($elements);
So the results something like this:
Array
(
[buyer] => abcd
)
So what I want to do. I want to echo just buyer and error message after this code: $checks = json_decode($file, true);
The error result is here:
{"data":{"error":404,"description":"No sale belonging to the current user found with that code"}}
Like for example:
if(buyer){echo 'true';}
if(error message){echo 'error';}
I guess you can check with array_key_exists if there is error. You can do something like this:
$checks = json_decode($file, true);
$data = $checks['data'];
if (array_key_exists("error", $data))
echo $data["description"];
else
echo $data["buyer"];
I am trying to build an array of xml files.
Each get request gives me 100 products and I need to get around 800 products.
So I tried building a loop based on a variable ts_d which u can use to get the next page of the xml.
public function getXml($division, $topic, $tsp)
{
$array = array();
$i = 0;
$x = 1;
while ($x = 1) {
$headers = ['Authorization' => 'Bearer '.$this->getAccessToken()];
$client = new Client([
'base_uri' => 'https://start.exactonline.nl/docs/',
]);
try {
$response = $client->request('GET', 'XMLDownload.aspx', [
'query' => ['Topic' => $topic, '_Division_' => $division, 'TSPaging' => $tsp],
'headers' => $headers,
]);
$string = new \SimpleXMLElement((string) $response->getBody());
$tspaging = $string->Topics->Topic->attributes()->{'ts_d'};
$array[$i]=$string;
echo $tspaging . ' ' . $tsp;
}
catch (\Exception $e) {}
if (!isset($tspaging)) {
$x = 0;
}
$i++;
$tsp = $tspaging
unset($string);
}
return $array;
}
I call this function with:
$stockPositions = $connection->getXml(1310477, 'StockPositions', '');
But this while loop is infinite and the echo returns:
0x000000000F5753AB 0x000000000F5753AB 0x000000000F5753AB0x000000000F5753AB 0x000000000F5753AB0x000000000F5753AB 0x000000000F5753AB0x000000000F5753AB 0x000000000F5753AB0x000000000F5753AB
Can you guys help met get out of this infinite loop?
The problem was that $tspaging was returning a simpleXmlObject string instead of a normal string. The solution was adding strval to that element:
$tspaging = strval($string->Topics->Topic->attributes()->{'ts_d'});
I have inbound return data -> http://php.net/manual/en/function.json-decode.php that is in PhP array format. The file data is the same type. It is just $result from the previous cycle.
$result = api_query("mytrades", array("marketid" => $id));
How do I compare $result array with $file array and then over write FILE with $result data?
In other words, FILE and the data it contains is continuously being updated with $result
compare -> overwrite -> repeat at next execution.
I tried array_diff but it does not like my data types and I cannot find a work around.
Note: .db file is empty at first cycle but becomes populated at first write.
sample code with Array to string conversion error:
<?php
$id = 155;
require_once('phpPlay.php');
$result = api_query("mytrades", array("marketid" => $id));
$lines = file("myDB.db");
$arrayDiffresult = array_diff ( $result, $lines);
var_dump($result);
file_put_contents('myDB.db', print_r($result, true));
?>
var_dump($result);
I think, you looking for some serialization, json_encoding for example.
$result = array(
'return' => array(
array(
"tradeid" =>"74038377",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"197009493",
),
array(
"tradeid" =>"2",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"2",
)
)
);
function getdiff($new, $old)
{
//implement right logical diff here
$diff = array();
$old_serialized = array();
foreach ($old as $item) {
$old_serialized[] = json_encode($item);
}
foreach ($new as $item) {
if (in_array(json_encode($item), $old_serialized)) {
continue;
}
$diff[] = $item;
}
return $diff;
}
$old = file_exists('1.db') ? json_decode(file_get_contents('1.db'), 1) : array();
$arrayDiffresult = getdiff($result['return'], $old);
file_put_contents('1.db', json_encode($result['return']));
print_r($arrayDiffresult);
I'm trying to filter an array (derived from a json object), so as to return the array key based on the value. I'm not sure if array search $key = array_search($value, $array); is the best way to do this (I can't make it work), and I think there must be a better way.
So far I've got this, but it isn't working. Grateful for any help!
public function getBedroomData(array $data,$num_beds = null,$type) {
$data = (array) $data;
if($num_beds > 0) {
$searchstring = "avg_".$num_beds."bed_property_".$type."_monthly";
} else {
$searchstring = "avg_property_".$type."_monthly";
}
$avg_string = array_search($data, $searchstring);
return $avg_string;
}
The array consists of average property prices taken from the nestoria api as follows:
http://api.nestoria.co.uk/api?country=uk&pretty=1&action=metadata&place_name=Clapham&price_type=fixed&encoding=json
This returns a long json object. My problem is that the data isn't consistent - and I'm looking for the quickest (run time) way to do the following:
$data['response']['metadata']['0'] //= data to return, [0] unknown
$data['response']['metadata']['0']['metadata_name'] = "avg_1bed_property_rent_monthly" //= string I know!
$data['response']['metadata']['1'] //= data to return, [1] unknown
$data['response']['metadata']['1']['metadata_name'] = "avg_1bed_property_buy_monthly" //= string I know!
$data['response']['metadata']['2'] = //= data to return, [2] unknown
$data['response']['metadata']['2']['metadata_name'] = "avg_2bed_property_buy_monthly" //= string I know!
.....
.....
.....
$data['response']['metadata']['10'] = avg_property_rent_monthly
$data['response']['metadata']['11'] = avg_property_buy_monthly
$data['response']['metadata'][most_recent_month] = the month reference for getting the data from each metadata list..
It isn't possible to filter the initial search query by number of bedrooms as far as I can work out. So, I've just been array slicing the output to get the information I've needed if bedrooms are selected, but as the data isn't consistent this often fails.
To search inside that particular json response from nestoria, a simple foreach loop can be used. First off, of course call the json data that you need. Then, extract the whole data, the the next step if pretty straightforward. Consider this example:
$url = 'http://api.nestoria.co.uk/api?country=uk&pretty=1&action=metadata&place_name=Clapham&price_type=fixed&encoding=json';
$contents = file_get_contents($url);
$data = json_decode($contents, true);
$metadata = $data['response']['metadata'];
// dummy values
$num_beds = 1; // null or 0 or greater than 0
$type = 'buy'; // buy or rent
function getBedroomData($metadata, $num_beds = null, $type) {
$data = array();
$searchstring = (!$num_beds) ? "avg_property_".$type."_monthly" : "avg_".$num_beds."bed_property_".$type."_monthly";
$data['metadata_name'] = $searchstring;
$data['data'] = null;
foreach($metadata as $key => $value) {
if($value['metadata_name'] == $searchstring) {
$raw_data = $value['data']; // main data
// average price and data points
$avg_price = 0;
$data_points = 0;
foreach($raw_data as $index => $element) {
$avg_price += $element['avg_price'];
$data_points += $element['datapoints'];
}
$data_count = count($raw_data);
$price_average = $avg_price / $data_count;
$data_points_average = $data_points / $data_count;
$data['data'][] = array(
'average_price' => $price_average,
'average_datapoints' => $data_points_average,
'data' => $raw_data,
);
}
}
return $data;
}
$final = getBedroomData($metadata, $num_beds, $type);
print_r($final);
After a lot of trial and error, I have finally managed to fetch tweets with Twitters new API (version 1.1). I'm using the PHP TwitterOauth library. Even though I'm able to fetch tweets, two things I do not understand.
The limit for statuses/user_timeline is 200 tweets. How do I loop through the results to fetch the maximum number of 3,200 tweets? I read something about making multiple GET requests, but I'm not sure how to do that.
It seems the number of tweets fetched varies randomly, and seldomly actually gets up to the number specified in the parameter 'count'. Why is that?
My application simply lets the visitor type in a username and fetch the tweets of that user. Here's my code.
if (isset($_GET['user'])) {
$user = $_GET['user'];
$content = $connection->get("statuses/user_timeline", array('count' => 200, 'exclude_replies' => true, 'screen_name' => $user));?>
$j = 0;
foreach ($content as $tweet) {
echo $j.' '.$tweet->text. '<br />';
$j++;
}
}
UPDATE: After trying out queremys suggestion below, I came up with a really ugly looking "solution" that has several major drawbacks. At least it shows the maximum amount of 3,200 tweets (and some duplicates). The result will look weird if the twitter account in question has less than 3,200 tweets. Anyways, just thought I'd share it if it can be of inspiration.
if (isset($_GET['user'])) {
$user = $_GET['user'];
$content = $connection->get('statuses/user_timeline', array(
'count' => 200, 'exclude_replies' => true, 'screen_name' => $user, 'include_rts' => 1
));
$x = 0;
while ($x < 15) {
$text = array();
foreach ($content as $tweet) {
$text[] = $tweet->id_str;
echo $tweet->text.'<br />';
}
$last_tweet = end($text);
$content = $connection->get('statuses/user_timeline', array(
'count' => 200, 'exclude_replies' => true, 'screen_name' => $user, 'include_rts' => 1, 'max_id' => $last_tweet
));
foreach ($content as $tweet) {
echo $tweet->text.'<br />';
}
$x++;
}
}
It could be a little bit pricy but i think possible (you can test something like that);
$contents = array();
$limit = 3200;
$max_id = null;
for ($count = 200; $count < $limit; $count += 200) {
if (null !== $max_id && $max_id == '') {
break;
}
$content = $connection->get('statuses/user_timeline', array(
'count' => $count, 'exclude_replies' => true, 'screen_name' => $user,
'max_id' => $max_id
));
$contents[] = $content;
// this indicates the last index of $content array
$max_id = $content[count($content) - 1]->id_str;
}
UPDATE!
You need to make $max_id to continue loop, and need to $max_id NULL to break loop.
// option 1, makes $max_id NULL silently
# $max_id = $content[count($content) - 1]->id_str;
// option 2, search for last index of array
if (count($content)) {
$last_tweet = end($content);
$max_id = $last_tweet->id_str;
} else $max_id = null;