I am getting this json output from yahoo boss api. It goes on for 50 results, but, I have pasted only the first two...
(
[bossresponse] => stdClass Object
(
[responsecode] => 200
[web] => stdClass Object
(
[start] => 0
[count] => 50
[totalresults] => 2750000
[results] => Array
(
[0] => stdClass Object
(
[date] =>
[clickurl] => http://www.apple.com/ipad/
[url] => http://www.apple.com/ipad/
[dispurl] => www.apple.com/<b>ipad</b>
[title] => Apple - <b>iPad</b>
[abstract] => <b>iPad</b> is a magical window where nothing comes between you and what you love. And it comes in two sizes.
)
[1] => stdClass Object
(
[date] =>
[clickurl] => http://en.wikipedia.org/wiki/IPad
[url] => http://en.wikipedia.org/wiki/IPad
[dispurl] => en.wikipedia.org/wiki/<b>IPad</b>
[title] => <b>iPad</b> - Wikipedia, the free encyclopedia
[abstract] => The <b>iPad</b> is a line of tablet computers designed and marketed by Apple Inc., which runs Apple's iOS operating system. The first <b>iPad</b> was released on April 3, 2010; the ...
)
[2] => stdClass Object
(
[date] =>
[clickurl] => http://www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3Aipad
[url] => http://www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3Aipad
[dispurl] => www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3A<b>ipad</b>
[title] => Amazon.com: <b>ipad</b>
[abstract] => Considering an <b>iPad</b>? Compare it to Kindle Fire HD Check out our easy side-by-side comparison chart to see how the newest <b>iPad</b> stacks up to Kindle Fire HD 8.9".
)
I use the following code in php to connect to the api and display the results...
**//connect to yahoo api and get results in json**
<?php
require("OAuth.php");
$cc_key = "**confidential**";
$cc_secret = "**confidential**";
$url = "http://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = "yahoo";
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
$results = json_decode($rsp);
?>
**// Present results in html/php**
<div id="resultsdiv">
<?php
foreach($results->bossresponse->web->results as $result)
{
echo '<h3><a href='.$result->url.'>'.$result->title.'</br>'.$result->abstract.'</a></h3>';
}
?>
My question is how do I paginate results, since all the 50 results appear on the first web page only. I want to display ten results in every page.
Any help is appreciated.
Thanks.
According to the Yahoo! BOSS documentation, specifically the Universal Arguments section, it looks like you can use the start and count parameters to adjust the pagination of results. It looks like the default return count is 50 which matches what you observed.
In your code example you can adjust by adding:
$args["start"] = 0; // increment as needed
$args["count"] = 10;
Related
I'm using PHP to send browser notifications through cURL (with Firebase) and while notifications are sent to their destination (desktop and mobile browsers), I'm facing two problems:
Each time I send a notification, I get two notifications in the browser. One with the content I have defined (see below) and one empty but considered as a background notification. I think it has something to do with active window but I don't know how to go around this.
When I click on the notification I have received, the link is never working.
I use the following code to send the notification:
$msg = urlencode($message);
$
$data = array(
'title'=>"My title",
'sound' => "default",
'msg'=>"my message",
'data'=>$datapayload,
'body'=>"message",
'color' => "#FF33CC",
'link' => "mylink"
);
if($img)
{
$data["image"] = "xxx";
$data["style"] = "picture";
$data["picture"] = "xxx";
}
$fields = array(
'to'=>$to,
'notification'=>$data,
"priority" => "high",
"link"=>"mylink",
"data"=>$data
);
$headers = array(
'Authorization: key=xxxx',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close( $ch );
When I send notifications with this script, I get the following output from the cURL request:
{"multicast_id":xxx,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"xxx"}]}
And here is an example of the JSON send to FCM:
Array
(
[to] => xxx
[notification] => Array
(
[title] => Notification pour Chrome Samsung
[sound] => default
[msg] => blablabla
[data] => Array
(
[ID] => xxxx
)
[body] => blablabla
[color] => #FF33CC
[link] => https://www.something.com
[image] => https://www.something.com/logo.png
[style] => picture
[picture] => https://www.something.com/logo.png
)
[priority] => high
[link] => https://www.something.com
[data] => Array
(
[title] => blabla
[sound] => default
[msg] => blablabla
[data] => Array
(
[ID] => 653804269445
)
[body] => blablabla
[color] => #FF33CC
[link] => https://www.something.com
[image] => https://www.something.com/logo.png
[style] => picture
[picture] => https://www.something.com/logo.png
)
)
I have tried to use only data or only notification but I still end up with 2 non clickable messages. I saw "click_action" in the documentation but it looks like it was only to be used for Android devices.
Any idea?
Thanks!
Update: the generic messages I get in the notification are obviously coming from the service worker but no matter what I do, updating the service worker doesn't seem to change anything.
I tried to do my first API calls which worked finally with help from this great users here in this community. Thanks again. I want to choose data[1] or the currency with symbol. So i could use a $variable from my CMS. Maybe someone can show me a way how i can change this call to symbol. Here is my API call.
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
$price = $json->data[1]->quote->USD->price; echo $price;
You get the data block IDs with array_column(), then you get the symbol's data block ID with array_search():
$data_ids = array_column($json->data, 'symbol');
$symbol_data_id = array_search('ETH', $data_ids);
$price = $json->data[$symbol_data_id]->quote->USD->price;
Or as an oneliner:
$price = $json->data[array_search('ETH', array_column($json->data, 'symbol'))]->quote->USD->price;
LATER UPDATE: OK, let me elaborate on this. Step by step:
You need a proper URL to acces the API. For this you need the API documentation. Your original question mentioned
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
while for your comment question you need something like
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?symbol=ETH";
A proper URL will give you a JSON response structured according to its purpose. You have this part ironed out, so I'll not insist on this. From your question text:
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: 1b58ff56-58b2-4fd0-b184-f9c3dd4ff106',
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, [
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1, // ask for raw response instead of bool
]);
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
Then you have to decide how to use the response. For me, the fastest way is to look at its structure (var_dump($json) or print_r($json)). Which will give something like this (the original question):
stdClass Object
(
[status] => stdClass Object
(
[timestamp] => 2021-11-06T18:37:59.447Z
[error_code] => 0
[error_message] =>
[elapsed] => 22
[credit_count] => 1
[notice] =>
[total_count] => 7060
)
[data] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Bitcoin
[...]
)
[1] => stdClass Object
(
[id] => 1027
[name] => Ethereum
[symbol] => ETH
[slug] => ethereum
[...]
[quote] => stdClass Object
(
[USD] => stdClass Object
(
[price] => 4445.0743486785
[volume_24h] => 14137477206.072
[volume_change_24h] => -9.6622
[percent_change_1h] => 0.2898806
[percent_change_24h] => -1.29677209
[percent_change_7d] => 3.13286959
[percent_change_30d] => 23.49191199
[percent_change_60d] => 28.79913805
[percent_change_90d] => 48.37310902
[market_cap] => 525560956659.07
[market_cap_dominance] => 19.5198
[fully_diluted_market_cap] => 525560956659.07
[last_updated] => 2021-11-06T18:37:03.000Z
)
)
)
[2] => stdClass Object [...]
or this (the question in the comment):
stdClass Object
(
[status] => stdClass Object
(
[timestamp] => 2021-11-06T18:03:05.201Z
[error_code] => 0
[error_message] =>
[elapsed] => 12
[credit_count] => 1
[notice] =>
)
[data] => stdClass Object
(
[ETH] => stdClass Object
(
[id] => 1027
[name] => Ethereum
[symbol] => ETH
[category] => coin
[description] => Ethereum (ETH) is a cryptocurrency . Users are able to generate ETH through the process of mining. Ethereum has a current supply of 118,233,336.749. The last known price of Ethereum is 4,424.33123326 USD and is down -1.39 over the last 24 hours. It is currently trading on 4537 active market(s) with $14,138,162,060.93 traded over the last 24 hours. More information can be found at https://www.ethereum.org/.
[...]
[platform] =>
[date_added] => 2015-08-07T00:00:00.000Z
[twitter_username] => ethereum
[is_hidden] => 0
)
)
)
So data is a property of the $json object.
In the first case, data is an array and its structure suggests using array functions to retrieve specific data.
In the second case, data and ETH are objects, while description is a property of ETH. Which allows me to get the description using object syntax
$description = $json->data->ETH->description;
What I want to achieve is unserialize all the data I am getting from the below link and get it converted to php array
http://ip-api.com/php
I know I can use unserialize() function of php and pass the serialized string to get it converted.
how can I convert the response of above link to php array ?
thanks
I generally use curl to get the content from external link
Do the following
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, 'http://ip-api.com/php');
$contents = curl_exec($c);
curl_close($c);
print_r(unserialize($contents));
your result array will look like below
Array ( [query] => 43.231.208.107 [region] => [timezone] => Asia/Kathmandu [org] => ClassicTech Pvt. [as] => AS55915 Classic Tech Pvt. Ltd. [city] => Kathmandu (Koteshwor) [zip] => [isp] => ClassicTech Pvt. [status] => success [lat] => 27.684499740601 [lon] => 85.34839630127 [country] => Nepal [countryCode] => NP [regionName] => Central Region )
also you can create a function and pass the url if you like to clean up the code.
You can also use file_get_contents() to archive this.
$result = file_get_contents('http://ip-api.com/php');
var_dump(unserialize($result));
I've been working on this SoundCloud website for awhile now and have just got into creating a stream page alternative that will display on our website. I have stumbled into an issue however and I'm sure it's an easy solution I'm just now figuring out how 2 achieve the proper output.
$user_ID = $_GET['id'];
$sc = curl_init();
curl_setopt($sc, CURLOPT_URL, 'http://api.soundcloud.com/users/'.$user_ID.'/followings?client_id='.$client_ID.'&page_size=200&cursor=1419617528000');
curl_setopt($sc, CURLOPT_HEADER, 0);
curl_setopt($sc, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($sc);
curl_close($sc);
$content = json_decode($output, true);
As you can see above the code currently is suppose to display up to 400 users in which someone is following, however when we do the following 2 return all of the content which is being displayed on that link.
echo "<pre>";
print_r($content);
echo "</pre>";
It appears that it caps at only 200 results ( which is really not that good we need 2 find an alternative 2 display the full amount of users someone is following. ) at the bottom of th page it displays another message.
[199] => Array
(
[avatar_url] => http://a1.sndcdn.com/images/default_avatar_large.png?1485508269
[id] => 72067899
[kind] => user
[permalink_url] => http://soundcloud.com/berthalie30
[uri] => https://api.soundcloud.com/users/72067899
[username] => berthalie30
[permalink] => berthalie30
[last_modified] => 2016/04/06 21:53:03 +0000
[first_name] =>
[last_name] =>
[full_name] =>
[city] =>
[description] =>
[country] =>
[track_count] => 0
[public_favorites_count] => 0
[followers_count] => 21
[followings_count] => 89
[plan] => Free
[myspace_name] =>
[discogs_name] =>
[website_title] =>
[website] =>
[reposts_count] => 32
[comments_count] => 0
[online] =>
[likes_count] => 0
[playlist_count] => 6
)
)
[next_href] => https://api.soundcloud.com/users/24537746/followings?client_id=XXXX&page_size=200&cursor=1406526915000
However, even using this method does nothing (even though I'm more then certain the user I am testing with has more then 200 users he's following.)
EDIT : Someone here is having the same issue, how ever I don't understand the comment solution on how 2 prevent it from happening..
I am able to retrieve results from yahoo with my API key, using the instructions found on the yahoo developers website. http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html#
Code:
if ($_POST['query'])
{
$newline="<br />";
$query = urlencode("'{$_POST['query']}'");
require("OAuth.php");
$cc_key = "key goes here";
$cc_secret = "secret goes here";
$url = "http://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = "$query";
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$rsp = curl_exec($ch);
$results = json_decode($rsp);
print_r($results);
}
Using print_r($results) as shown above, I get results, such as the following (extract of first three results shown from searching for "elephant"):
PLEASE NOTE I HAVE CHANGED THE URLS TO "WWW" AS I REQUIRE AT LEAST 10 REPUTATION TO POST MORE THAN 2 LINKS.
stdClass Object ( [bossresponse] => stdClass Object ( [responsecode]
=> 200 [web] => stdClass Object ( [start] => 0 [count] => 50 [totalresults] => 36800000 [results] => Array ( [0] => stdClass Object
( [date] => [clickurl] => WWW [url]
=> WWW [dispurl] => en.wikipedia.org/wiki/Elephant [title] => Elephant - Wikipedia, the
free encyclopedia [abstract] => Elephant trunks have multiple
functions, including breathing, olfaction, ... One elephant has been
observed to graze by kneeling on its front legs, ... ) [1] => stdClass
Object ( [date] => [clickurl] =>
WWW [url] =>
WWW [dispurl] =>
www.defenders.org/elephant/basic-facts [title] => Elephant | Basic
Facts About Elephants | Defenders of Wildlife [abstract] => Elephant.
Basic Facts About Elephants More on Elephant: Threats to Elephants ยป
More on Elephant: Basic Facts . Threats. What Defenders Is Doing to
Help. What You Can ... ) [2] => stdClass Object ( [date] => [clickurl]
=> WWW
[url] =>
WWW
[dispurl] => kids.nationalgeographic.com/.../african-elephant [title]
=> African Elephant Facts and Pictures -- National Geographic Kids [abstract] => Kids' feature about elephants, with photographs, video,
audio, fun facts, an e-mail postcard, and links to other animals. )
[3] => stdClass Object ( [date] => [clickurl] =>
WWW [url]
=> WWW [dispurl] => elephant.elehost.com/About_Elephants/about_elephants.htm
[title] => About Elephants [abstract] => All about elephants on the
Elephant Information Repository! This page includes a summary of
elephant related facts to get you inducted in to the world of
elephants. )
I have attempted to output the results, in a legible format, as follows:
Code Attempt 1:
foreach ($results->{ 'results' } as $item )
{
echo "<font color ='blue'>{$item->{ 'title' }}</font>".": "."$newline"."$newline".$item->{ 'abstract' }."\n\n";
}
I also tried the following, without success:
Code Attempt 2:
echo $results['results']['url'];
echo $results['results']['title'];
echo $results['results']['abstract'];
Any ideas on what to do?
Thanks.
I've noticed you just copy-pasted the code from the documentation's code examples, but never mind that.
You're accessing the results array the wrong way:
foreach ($results->bossresponse->web->results as $result)
{
//do stuff
echo $result->title.'<br/>';
}
Or, as cptnk suggested:
$results = json_decode($rsp, true);
//force to assoc-array, which will allow array-access
foreach($results['bossresponse']['web']['results'] as $result)
{
//$result is array here, but do the same stuff
echo $result['title'].'<br/>';
}
Or, combine the two
foreach($results->bossresponse->web->results as $result)
{
$result = (array) $result;//casts stdClass to array
printf('%s<br/>', $result['url'], $result['title']);
}