I'm relatively new to mediawiki and has just started last week.
Anyone can point me to the correct direction of getting the top article (based on number of likes) in mediawiki? I've already implemented the fblikebutton extension on every article and managed to retrieve the number of likes for each article.
Code that I used to check the number of likes in each article on different URLS
$query_for_fql = "SELECT like_count FROM link_stat WHERE url = '".$full_url."'";
$fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($query_for_fql);
$response = file_get_contents($fqlURL);
$json_data = json_decode($response);
$fb_like_count = $json_data[0]->like_count;
echo 'Facebook Like:'.$fb_like_count .'<br/>';
eg:
example.com/wiki/index.php?title=ABC (1 like)
example.com/wiki/index.php?title=XYZ (2 likes)
I tried this but this is not working
$highest = 0;
while($highest < $fb_like_count)
{
if($fb_like_count > $highest) //if loop at first
{
$highest = $fb_like_count;
echo "highest value is " . $highest . '<br/>';
}
}
I want to retrieve the content in example.com/wiki/index.php?title=XYZ and display in the "Top Article Page". What should I do next after retrieving the number of likes for each article on each url. The extensions I found for top articles are based on the number of views. But I want to classify the top article based on number of likes.
Thanks a million for helping!
As I said in my comment to you question, FQL is deprecated, and the https://api.facebook.com/method/fql.query endpoint as well.
If you want something future-proof, then you should switch to the /?ids={url1},{url2},... endpoint. You can use this one to generate the comma-separated list of URLs inn the forehand, and then retrieve all the shares in one request, for example
GET /?ids=http://www.techcrunch.com,http://www.google.com
returns
{
"http://www.techcrunch.com": {
"og_object": {
"id": "433841427570",
"title": "TechCrunch",
"type": "website",
"updated_time": "2015-05-27T21:31:39+0000",
"url": "http://techcrunch.com/"
},
"share": {
"comment_count": 0,
"share_count": 20914
},
"id": "http://www.techcrunch.com"
},
"http://www.google.com": {
"og_object": {
"id": "381702034999",
"description": "Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.",
"title": "Google",
"type": "website",
"updated_time": "2015-05-28T07:10:18+0000",
"url": "http://www.google.com/"
},
"share": {
"comment_count": 2,
"share_count": 12340803
},
"id": "http://www.google.com"
}
}
The sorting issue you have is not related to the Facebook API, but PHP.
See
https://developers.facebook.com/docs/graph-api/reference/v2.3/url
Sort JSON object in PHP by a key value
How to sort JSON objects by a certain key's value
Related
I have a problem with fetching the correct data from a decoded JSON file. I don't know if my question is correct since I don't really know what I am doing for the moment.
So, this is what I don't want to do.
$ln = 'https://api.steamprices.net/v2/csgoprices/?id='.market_hash_name.'&key=XXX';
$link1 = file_get_contents($ln);
$myarray1 = json_decode($link1, true);
echo $myarray1['median_price'];
I am trying to get the price for every steam skin that's being loaded in my code. What this code does is that it loads this api link for every item I load. So if I have 50 items, this link will be loaded 50 times, which is not accepted by the API.
What I want to do, is that I want to load it once, and fetch the prices for every item from that exact link. That link would look like this:
https://api.steamprices.net/v2/csgoprices/?&key=XXX
So, lets say I load it once, and then when I want to apply market_hash_name to it, how do I do?
I assume it is something like this.
$priceJson = file_get_contents('https://api.steamprices.net/v2/csgoprices/?key=XXX');
$priceData = json_decode($priceJson, true);
echo $priceData[''.$market_hash_name.'']['price'];
But it doesn't seem to work. I am sorry for this messy explanation, I an unfamiliar with this.
Note that an example response for the api link looks like this:
{
"-r-H1Z1 Shirt": {
"price": 0.11,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3dxC3m4m0ihzss0MKE6NtIt4qs-JukOX73WgETXYze_pxEBA",
"game": "h1z1"
},
"2016 Invitational Crate": {
"price": 0.09,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6APSjJ6BjX9rGBYZ9ioCPzysSX6hNNacA",
"game": "h1z1"
},
"ANGRYPUG Motorcycle Helmet": {
"price": 0.17,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3WySnxyXoUgz870MKd7sFTkZq98oW1ORiqAVsCUYfbNu3SUQqvUSGyY__iEw",
"game": "h1z1"
},
Another output
{
"name":"Aces High Pin",
"price":1210,
"have":2,
"max":9,
"rate":95,
"tr":0
}
Well, the json string you provide isn't valid but something like this may help you
<?php
$jsonData=file_get_contents("json.file"); // simply contains your json string as posted
$jsonArray=json_decode($jsonData,true);
$jsonObject=json_decode($jsonData);
$list_of_MHN=array("2016 Invitational Crate","ANGRYPUG Motorcycle Helmet");
print_r($jsonArray);
exit;
foreach($jsonArray as $hash_name=>$arr){
if(in_array($hash_name,$list_of_MHN)){
print_r($arr);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonArray[$list_of_MHN[$i]])){
print_r($jsonArray[$list_of_MHN[$i]]);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonObject->$list_of_MHN[$i])){
print_r($jsonObject->$list_of_MHN[$i]);
}
}
?>
I am unable to fetch desired data of title, score from the json_decode array, I have tried all the ways which are already discussed in stackoverflow. Can anyone help me..
$myKEY = "xyz";
$url_req= 'google api request here';
$results= checkPageSpeed($url_req_d);
$googleapi = json_decode($results,true);
Google api send the data like this when var_dump($googleapi) and I need to fetch title and score values from the array. Please reply suggested code to extract title and score values i.e "xyz" and "73"
{
"kind": "pagespeedonline#result",
"id": "www xyz com/",
"responseCode": 200,
"title": "xyz",
"ruleGroups": {
"SPEED": {
"score": 73
}
},
"pageStats": {
"numberResources": 67,
"numberHosts": 15,
"totalRequestBytes": "9354",
"numberStaticResources": 48,
"htmlResponseBytes": "129210",
"textResponseBytes": "5647",
"cssResponseBytes": "142839",
"imageResponseBytes": "411466",
"javascriptResponseBytes": "635453",
"otherResponseBytes": "94639",
"numberJsResources": 17,
"numberCssResources": 6
}, .........
$googleapi['title'] and $googleapi['ruleGroups']['SPEED']['score'] should do the trick. Check the documentation for more information on how you can access elements from multidimensional arrays.
I know this is probably a simple question, but I have been struggling with this for a few hours without any solution. I calling the Facebook Graph API and getting a result like so:
{
"og_object": {
"id": "1060581720684416",
"description": "It's\u00a0a chance to donate to your local shelter, volunteer with animals or simply cuddle up to your furry friend.",
"title": "National Dog Day 2016 Quotes: 15 Sayings And Photos Celebrating Man's Best Friend",
"type": "article",
"updated_time": "2016-08-26T19:26:39+0000"
},
"share": {
"comment_count": 0,
"share_count": 481
},
"id": "http://www.ibtimes.com/national-dog-day-2016-quotes-15-sayings-photos-celebrating-mans-best-friend-2407163"
}
I am only interested in accessing the "share_count" and "comment_count" values from this array. Here is the PHP I am trying to use:
$searchTopFBCount = 'https://graph.facebook.com/' . $thisFBLink . '?access_token=xxxxxxxxxx';
$getthisContents = file_get_contents($searchTopFBCount);
$jsonTopFBCount = json_decode($getthisContents,true);
$jsonTopShares = $jsonTopFBCount[0][share]->share_count;
$jsonTopComments = $jsonTopFBCount[0][share]->comment_count;
$jsonTopFBTotal = $jsonTopShares + $jsonTopComments;
No matter what I try, I can't seem to get any values for $jsonTopShares and $jsonTopComments. Any help anyone can give me with this problem would be much appreciated!
As someone mentioned in the comments, I'm not sure why you're using [0] as your data isn't in a nested array. You're also trying to access the array properties like they're objects.
Try this instead:
$jsonTopShares = $jsonTopFBCount['share']['share_count'];
$jsonTopComments = $jsonTopFBCount['share']['comment_count'];
I am using PHP on shared server to access external site via API that is returning JSON containing 2 levels of data (Level 1: Performer & Level 2: Category array inside performer). I want to convert this to multidimensional associative array WITHOUT USING json_decode function (it uses too much memory for this usage!!!)
Example of JSON data:
[
{
"performerId": 99999,
"name": " Any performer name",
"category": {
"categoryId": 99,
"name": "Some category name",
"eventType": "Category Event"
},
"eventType": "Performer Event",
"url": "http://www.novalidsite.com/something/performerspage.html",
"priority": 0
},
{
"performerId": 88888,
"name": " Second performer name",
"category": {
"categoryId": 88,
"name": "Second Category name",
"eventType": "Category Event 2"
},
"eventType": "Performer Event 2",
"url": "http://www.novalidsite.com/somethingelse/performerspage2.html",
"priority": 7
}
]
I have tried to use substr and strip the "[" and "]".
Then performed the call:
preg_match_all('/\{([^}]+)\}/', $input, $matches);
This gives me the string for each row BUT truncates after the trailing "}" of the category data.
How can I return the FULL ROW of data AS AN ARRAY using something like preg_split, preg_match_all, etc. INSTEAD of the heavy handed calls like json_decode on the overall JSON string?
Once I have the array with each row identified correctly, I CAN THEN perform json_decode on that string without overtaxing the memory on the shared server.
For those wanting more detail about json_decode usage causing error:
$aryPerformersfile[ ] = file_get_contents('https://subdomain.domain.com/dir/getresults?id=1234');
$aryPerformers = $aryPerformersfile[0];
unset($aryPerformersfile);
$mytmpvar = json_decode($aryPerformers);
print_r($mytmpvar);
exit;
If you have a limited amount of memory, you could read the data as a stream and parse the JSON one piece at a time, instead of parsing everything at once.
getresults.json:
[
{
"performerId": 99999,
"name": " Any performer name",
"category": {
"categoryId": 99,
"name": "Some category name",
"eventType": "Category Event"
},
"eventType": "Performer Event",
"url": "http://www.novalidsite.com/something/performerspage.html",
"priority": 0
},
{
"performerId": 88888,
"name": " Second performer name",
"category": {
"categoryId": 88,
"name": "Second Category name",
"eventType": "Category Event 2"
},
"eventType": "Performer Event 2",
"url": "http://www.novalidsite.com/somethingelse/performerspage2.html",
"priority": 7
}
]
PHP:
$stream = fopen('getresults.json', 'rb');
// Read one character at a time from $stream until
// $count number of $char characters is read
function readUpTo($stream, $char, $count)
{
$str = '';
$foundCount = 0;
while (!feof($stream)) {
$readChar = stream_get_contents($stream, 1);
$str .= $readChar;
if ($readChar == $char && ++$foundCount == $count)
return $str;
}
return false;
}
// Read one JSON performer object
function readOneJsonPerformer($stream)
{
if ($json = readUpTo($stream, '{', 1))
return '{' . readUpTo($stream, '}', 2);
return false;
}
while ($json = readOneJsonPerformer($stream)) {
$performer = json_decode($json);
echo 'Performer with ID ' . $performer->performerId
. ' has category ' . $performer->category->name, PHP_EOL;
}
fclose($stream);
Output:
Performer with ID 99999 has category Some category name
Performer with ID 88888 has category Second Category name
This code could of course be improved by using a buffer for faster reads, take into account that string values may themselves include { and } chars etc.
You have two options here, and neither of them include you writing your own decoder; don't over-complicate the solution with an unnecessary work-around.
1) Decrease the size of the json that is being decoded, or
2) Increase the allowed memory on your server.
The first option would require access to the json that is being created. This may or may not be possible depending on if you're the one originally creating the json. The easiest way to do this is to unset() any useless data. For example, maybe there is some debug info you won't need, so you can do unset($json_array['debug']); on the useless data.
http://php.net/manual/en/function.unset.php
The second option requires you to have access to the php.ini file on your server. You need to find the line with something like memory_limit = 128M and make the 128M part larger. Try increasing this to double the value already within the file (so it would be 256M in this case). This might not solve your problem though, since large json data could still be the core of your problem; this only provides a work-around for inefficient code.
Im looking to retrieve all of my friends hometowns, I am using similar PHP as that used to retrieve their names. I think the code im using should work but I think because some users havent set a hometown it wont work and says the for each argument is invalid (although this could be completely wrong).
When simply typing in the URL to the web browser I get the following structure:
{
"id": "z",
"friends": {
"data": [
{
"name": "x",
"hometown": {
"id": "x",
"name": "x"
},
"id": "x"
},
Which is then repeated for every user in the friend list, although for friends without a hometown the following is omitted:
"hometown": {
"id": "x",
"name": "x"
},
To retrieve the name and birthday I have used the following PHP:
$response2 = curl_exec($ch2);
$user2 = json_decode($response2, true);
$user3=$user2{'friends'};
$user4=$user3['data'];
echo ("<h2>Friend List</h2><br>");
foreach($user4 as $friend) {
echo $friend["name"] . "<br />" . $friend["birthday"] . "<br /><br />";
}
}
PS I know the variable names arent particularly good but I will change them once ive figured out what im doing for the hometown!
Thanks a lot for any help in advance.
Not everyone makes their hometown or location available to their friends. In that case you won't be able to get the data over the API and need to check for that.
To get a bit more data than just querying for the hometown, we also read out the current_location.
Through the Graph API you would use this resource: https://graph.facebook.com/me/friends?fields=hometown,location
If you are using FQL you can use a query like this:
SELECT uid, first_name, last_name, current_location, hometown_location, friend_count, mutual_friend_count FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())
Remember that you need the friends_location and friends_hometown permission to read these fields.