I don't know if the question is right, but here is my problem..
I want to crawl this site: https://www.easports.com/fifa/ultimate-team/compete/leaderboards to get the leaderboard data.
When I do so with the following code, I only get the header + footer, but not the leaderboard data.
$client = new HttpClient();
$client->setAdapter("Zend\Http\Client\Adapter\Curl");
$client->setUri("https://www.easports.com/fifa/ultimate-team/compete/leaderboards");
$content = $client->send()->getBody();
var_dump($content);
Is there a problem with my curl or can this data not be curled? If so, maybe you got a solution for me ;)
If you open the Developer Tools in your browser you can see which extra requests are done to get the leaderboard filled. You should use the url https://www.easports.com/cgw/api/fifa/fut/leaderboard?platform=xboxone®ion=ams&period=curr to get the leaderboard. This returns a JSON in the following layout:
[
{
"rank": 1,
"persona": "persona",
"hasProfile": false,
"wins": 1,
"skill": "6",
"qualified": 0
}]
Using your code this would be:
$client = new HttpClient();
$client->setAdapter("Zend\Http\Client\Adapter\Curl");
$client->setUri("https://www.easports.com/cgw/api/fifa/fut/leaderboard?platform=xboxone®ion=ams&period=curr");
$content = $client->send()->getBody();
var_dump($content);
Which can then be processed for example with:
$client = new HttpClient();
$client->setAdapter("Zend\Http\Client\Adapter\Curl");
$client->setUri("https://www.easports.com/cgw/api/fifa/fut/leaderboard?platform=xboxone®ion=ams&period=curr");
$content = $client->send()->getBody();
$leaderBoard = json_decode($content);
foreach($leaderBoard as $member){
echo $member['rank'] . '. ' . $member['persona'] . '(' . $member['wins'] . ' Wins)<br />';
}
Related
I can't seem to find any code to display returned values from the call.
I am running the xml-lib from the software vendor at the following link
https://support.sippysoft.com/support/solutions/articles/3000013653-xml-rpc-api-sign-up-html-page-fresh-version-
<?php
include 'xmlrpc/xmlrpc.inc';
function listAccounts()
{
//$params = array(new xmlrpcval(array("i_account"=> new xmlrpcval('14719', "string")), 'struct'));
$msg = new xmlrpcmsg('listAccounts');
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('https://DOMAINHERE/xmlapi/xmlapi');
$cli->setSSLVerifyPeer(false);
$cli->setSSLVerifyHost(false);
$cli->setCredentials('USERNAME', 'PASSWORD', CURLAUTH_DIGEST);
$r = $cli->send($msg, 20);
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
print_r ($r->faultString());
return false;
}
else
{
return $r->value();
// I need something here to write returned values to normal PHP variable
}
}
Ok thanks to the comment from halfer.
I managed to get the issue and digging through the code in the library I found a function that does the trick.
Thanks a million for your pointer it really helped.
I am new to php and xml and the learning curve is quite tall but thanks.
for someone else reference maybe in the future here is the corrected code with the last 2 lines that does the magic for me.
<?php
include 'xmlrpc/xmlrpc.inc';
// $params = array(new xmlrpcval(array("offset"=> new xmlrpcval("1", "int")
// ,"i_customer"=> new xmlrpcval("321", "int")
// ), 'struct'));
$params = array(new xmlrpcval(array("i_customer"=> new xmlrpcval("321", "int")
), 'struct'));
$msg = new xmlrpcmsg('listAccounts', $params);
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('DOMAIN');
$cli->setSSLVerifyPeer(false);
$cli->setdebug(0);
$r = $cli->send($msg, 20); /* 20 seconds timeout */
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
echo $r->faultString();
}
// now lets decode the xml response..
$values=php_xmlrpc_decode($r->value());
var_dump ($values['accounts'][0][username]);
?>
I have created this PHP script that print outs the specified number of latest youtube videos from a youtube channel. I'm setting the maxResults to 10 but it returns hundreds of results. Please go through the code and help.
<?php
$API_Url = 'https://www.googleapis.com/youtube/v3/';
$API_Key = '...';
$channelId = 'UCX6OQ3DkcsbYNE6H8uQQuVA';
$parameter = [
'id'=> $channelId,
'part'=> 'contentDetails',
'key'=> $API_Key
];
$channel_URL = $API_Url . 'channels?' . http_build_query($parameter);
$json_details = json_decode(file_get_contents($channel_URL), true);
$playlist=$json_details['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
$parameter = [
'part'=> 'snippet',
'playlistId' => $playlist,
'maxResults'=> 10,
'key'=> $API_Key
];
$channel_URL = $API_Url . 'playlistItems?' . http_build_query($parameter);
$json_details = json_decode(file_get_contents($channel_URL), true);
$my_videos = [];
foreach($json_details['items'] as $video){
//$my_videos[] = $video['snippet']['resourceId']['videoId'];
$my_videos[] = array( 'v_id'=>$video['snippet']['resourceId']['videoId'], 'v_name'=>$video['snippet']['title'] );
}
while(isset($json_details['nextPageToken'])){
$nxt_page_URL = $channel_URL . '&pageToken=' . $json_details['nextPageToken'];
$json_details = json_decode(file_get_contents($nxt_page_URL), true);
foreach($json_details['items'] as $video)
$my_videos[] = $video['snippet']['resourceId']['videoId'];
}
print_r($my_videos);
//foreach($my_videos as $video){
//if(isset($video)){
//echo '<a href="https://www.youtube.com/watch?v='. $video['v_id'] .'">
//<div>'. $video['v_name'] .'</div>
//</a><br><br><br>';
//}
//}
And the extra results it is returning don't even have a title or id. See the image for yourself
Here's a screenshot:
The reason you get so many items is that after the first request, you have a while loop that makes subsequent requests to the YouTube API for the next page of data until nextPageToken is not found in the response payload, meaning you can be making anything from 1 to tens or hundreds of requests depending on how many pages of data are available each bringing back up to 10 additional items.
Each individual request will be bringing back 10 items at a time as you specified, but the cumulative total is obviously a lot more than that. Since you're only interested in the first 10, simply removing the while block should stop the code from making any more requests after the first one and thus won't add them to the array.
I have a Discord servern with 1361 members and on my website I want to display a total number of joined users.
I have figured out how to get all online Members on the server using:
<?php
$jsonIn = file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json');
$JSON = json_decode($jsonIn, true);
$membersCount = count($JSON['members']);
echo "Number of members: " . $membersCount;
?>
What should I do differently to get a total number of ALL users that have joined the server, and not just display the online members?
Now, I realize I am reviving a pretty old thread here, but I figure some might still use an answer. As jrenk pointed out, you should instead access https://discordapp.com/api/guilds/356230556738125824/members.
Your 404: Unauthorized comes from the fact that you are -you guessed it- not authorized.
If you have created a bot, it is fairly easy: just add a request header Authorization: Bot YOUR_BOT_TOKEN_HERE. If you use a normal Discord account, the whole problem is a bit more tricky:
You will first have to send a POST request to https://discordapp.com/api/auth/login and set the body to {"email": "EMAIL_HERE", "password": "PASSWORD_HERE"}.
You will get a response with the parameter token. Save this token, you will need it later. BUT:
NEVER, UNDER ANY CIRCUMSTANCES show anyone this token, as it is equivalent to your login credentials!
With this token, you can now send a POST request to the same address: https://discordapp.com/api/auth/login, but now add the header Authorization: YOUR_BOT_TOKEN_HERE. Note the missing "Bot" at the beginning.
Also, what you mustn't forget:
If you don't add the parameter ?limit=MAX_USERS, you will only get the first guild member. Take a look here to see details.
You have to count the number of online member
here is the working code
<?php
$members = json_decode(file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json'), true)['members'];
$membersCount = 1;
foreach ($members as $member) {
if ($member['status'] == 'online') {
$membersCount++;
}
}
echo "Number of members: " . $membersCount;
?>
You need a bot on your discord server to get all members. Use the Discord js library for example.
First create a discord bot and get a token, see the following url:
https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token
As #2Kreeper noted, do not reveal your token publicly.
Then use the following code, replacing "enter-bot-token-here" and "enter-guild-id-here" with your own information:
<?php
$json_options = [
"http" => [
"method" => "GET",
"header" => "Authorization: Bot enter-bot-token-here"
]
];
$json_context = stream_context_create($json_options);
$json_get = file_get_contents('https://discordapp.com/api/guilds/enter-guild-id-here/members?limit=1000', false, $json_context);
$json_decode = json_decode($json_get, true);
echo '<h2>Member Count</h2>';
echo count($json_decode);
echo '<h2>JSON Output</h2>';
echo '<pre>';
print_r($json_decode);
echo '</pre>';
?>
For anyone still interested, here's the solution I currently use using RestCord:
use RestCord\DiscordClient;
$serverId = <YourGuildId>;
$discord = new DiscordClient([
'token' => '<YourBotToken>'
]);
$limit = 1000;
$membercnt = 0;
$_ids = array();
function getTotalUsersCount($ids, $limit, $serverId, $discord) {
if( count($ids) > 0 ) {
$last_id = max($ids);
$last_id = (int)$last_id;
} else {
$last_id = null;
}
$members = $discord->guild->listGuildMembers(['guild.id' => $serverId, 'limit' => $limit, 'after' => $last_id]);
$_ids = array();
foreach( $members as $member ) {
$ids[] = $member->user->id;
$_ids[] = $member->user->id;
}
if( count($_ids) > 0 ) {
return getTotalUsersCount($ids, $limit, $serverId, $discord);
} else {
return $ids;
}
}
$ids = getTotalUsersCount($_ids, $limit, $serverId, $discord);
$membercnt = count($ids);
echo "Member Count: " . $membercnt;
In addition to Soubhagya Kumar's answer comment by iTeY you can simply use count(), there is no need to loop if you do not require a loop.
I'm reviving this since it still seems to be relevant and the other answers seem a bit too complex I think (maybe the API used to be bad(?)). So:
Generate a permanent discord invite and keep the code at the end (https://discord.gg/xxxxxxx) and then all you do is this:
<?php
$server_code = "xxxxxxx";
$url = "https://discord.com/api/v9/invites/".$server_code."?with_counts=true&with_expiration=true";
$jsonIn = file_get_contents($url);
$json_obj = json_decode($jsonIn, $assoc = false);
$total = $json_obj ->approximate_member_count;
?>
And there you go, that's the total member count. Keep in mind, this will also count the bots I think so you have to account for that if you want to refine it even more
I would like to get the item URL based on the item ID. After searching, I found that I can use GetSingleItem to achieve my goal. However, I got an error:
eBay returned the following error(s):
2 : Unsupported API call.
The API call "GetSingleItem" is invalid or not supported in this release.
Here is my code (all configuration are correct because I can use GetOrders by using these configs):
$subverb = "GetSingleItem";
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetSingleItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= "<ItemID>111986554711</ItemID>";
$requestXmlBody .= '</GetSingleItemRequest>';
//Create a new eBay session with all details pulled in from included keys.php
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $subverb);
//send the request and get response
$responseXml = $session->sendHttpRequest($requestXmlBody);
if (stristr($responseXml, 'HTTP 404') || $responseXml == '')
die('<P>Error sending request');
//Xml string is parsed and creates a DOM Document object
$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
//get any error nodes
$errors = $responseDoc->getElementsByTagName('Errors');
$response = simplexml_import_dom($responseDoc);
$entries = $response->PaginationResult->TotalNumberOfEntries;
//if there are error nodes
if ($errors->length > 0) {
echo '<P><B>eBay returned the following error(s):</B>';
//display each error
//Get error code, ShortMesaage and LongMessage
$code = $errors->item(0)->getElementsByTagName('ErrorCode');
$shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
$longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
//Display code and shortmessage
echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
//if there is a long message (ie ErrorLevel=1), display it
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
} else { //If there are no errors, continue
if (isset($_GET['debug'])) {
header("Content-type: text/xml");
print_r($responseXml);
} else {
print("\n; 111986554711: " . $response->Item->ViewItemURLForNaturalSearch);
}
}
Any suggestion? Thank you .
As you discovered, you don't need the API to construct a simple eBay view item landing page URL.
The URL format you discovered works, but it's very old and might not be supported in full or for much longer.
Here's a simple URL format that is pretty current that you can use:
http://www.ebay.com/itm/122225724269
I got an answer without using api. Here is the answer: after I got item ID, I can use "http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=".$item_id to show my product on ebay.
I found this uri by using GetOrders API.
OrderArray.Order .TransactionArray.Transaction .Variation .VariationViewItemURL
Tip: "not optimized for natural search"
If anyone has any idea about "GetSingleItem", I am willing to know why my code doesn't work.
There is a code api url and it is output json format. I need cache my json result or different solution. Because my page when visiting new user it calling api again and page opening speeds consists of problems. How can i make it?
My Code:
<?php
$jsonurl = 'http://api.site.com/deal/browse.html?apiKey=VN43U6&p=2';
$json = file_get_contents($jsonurl, 0, null, null);
$json_output = json_decode($json);
foreach ($json_output->deals as $objects) {
$title = $objects->title;
echo '<h5 class="coupon-title">' . $title . '</h5>';
}
?>
If you want to use memcache as your cache service, you can try something like this:
$memcache = new Memcache;
$memcache->connect("localhost", 11211);
$hash = hash('sha256', $jsonurl);
$json = $memcache->get($hash);
if (!$json) {
$json = file_get_contents($jsonurl, 0, null, null);
$memcache->set($hash, $json, false, strtotime("+1 day"));
}
$json_output = json_decode($json);
Just cache it in a file :
$cache_json='yourfilename.json';
if(!is_file(cache_json)){
$json = file_get_contents($jsonurl, 0, null, null);
file_put_contents($cache_json,$json);
}
else{
$json = file_get_contents($cache_json);
}
$json_output = json_decode($json);
With this example the cache is infinite, you can just remove the cache file with a cron task or check the file creation timestamp with the php function filemtime to set a time limit for cache.
You can cache it in DB too with a table with 3 fields : key, value (json), timeout