I am receiving JSON that looks like this:
{
"result": "SUCCESS",
"message": {
"totalResults": 371711,
"resultsPerPage": 25,
"page": 1,
"data": [
{
"orderId": "8A62D2C05A",
"clientOrderId": "8A62D2C05A",
"shipCarrier": null,
"shipMethod": null,
"dateCreated": "2019-01-01 00:01:14",
"dateUpdated": "2019-01-27 10:44:57",
"orderType": "NEW_SALE",
"orderStatus": "COMPLETE",
"reviewStatus": "APPROVED",
"totalAmount": "9.93",
"avsResponse": null,
But I only get the 1st page of results, 25 items, with this code:
// curl stuff here
$rawresponse = curl_exec($curlSession);
$jrsp=json_decode($rawresponse,TRUE);
$result=$jrsp["result"];
$order_ct=$jrsp["message"]["totalResults"];
echo "Status $result for $order_ct orders.\n";
for ($i=0; $i<$order_ct; $i++) {
$cust_id=$jrsp["message"]["data"][$i]["customerId"];
$name=$jrsp["message"]["data"][$i]["name"];
$ord_dt=$jrsp["message"]["data"][$i]["dateCreated"];
$phone=$jrsp["message"]["data"][$i]["phoneNumber"];
$ord_amnt=$jrsp["message"]["data"][$i]["totalAmount"];
$item_ct=count($jrsp["message"]["data"][$i]["items"]);
echo "ID:$cust_id Name: $name Date:$ord_dt Phone:$phone Amnt: $ord_amnt Item:$item_ct\n";
}
All of the initial echo says, "Status: SUCCESS for 371711 orders." as expected, but I only get the first 25 data items. What do I need to do to get the other pages?
There is no "page" parameter in the api docs for the request, but I just found out from support the docs are incomplete. Jonnix and Barmar are both right. Thanks. I do need a for $pages loop to get all results.
Related
I am trying to add a JSON script to a php file in my sites admin. My goal is to have the JSON run when the order status is change to 3 (shipped).
I am pretty sure I am going about this all wrong but I am not sure what to do yet. here is my code:
if ( ($check_status['orders_status'] != $status) && $check_status['orders_status'] == 3) { ?>
<script>
POST https://api.yotpo.com/oauth/token
{
"client_id": "### Your client_id ###",
"client_secret": "### Your client_secret ###",
"grant_type": "client_credentials"
}
POST https://api.yotpo.com/myapi/purchases
{
"validate_data": true,
"platform": "general",
"utoken": "### YOUR UTOKEN ###",
"email": "client#abc.com",
"customer_name": "bob",
"order_id": "order_1",
"order_date": "2010-10-14",
"currency_iso": "USD",
"products": {
"SKUaaa12": {
"url": "http://example_product_url1.com",
"name": "product1",
"image": "http://images2.fanpop.com/image/photos/13300000/A1.jpg",
"description": "this is the description of a product",
"price": "100",
"specs": {
"upc": "USB",
"isbn": "thingy"
},
"product_tags": "books"
}
}
}
</script>
<?php } ?>
First of all, there is nothing in my code that says hey, this is JSON besides the tag.
do I need to have the json in a sepearate json file? Or do I need to convert this script to php?
First of all, Nikita is correct that JSON does not run - it is not script. It is a standardized way to store information.
PHP has native JSON handling functions and can easily take existing objects or arrays and convert them to JSON.
<?php
$json = json_encode($my_data);
?>
<input type="hidden" name="post_data" <?php echo 'value="'.$json.'" ?> />
Then when you send this variable $json to the next page, you'll unpack it like so
$my_data = json_decode($_POST['post_data']);
This is a pure PHP implementation, though JavaScript does nice functions to stringify to/from json as well.
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'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
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.
I'm using a YouTube data API request to grab the channel id, but i'm not too sure why it isn't working:
The returned JSON request i'm getting is:
{
"kind": "youtube#channelListResponse",
"etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/k5qSWj-xcF96jAN3p1uQH1amSRc\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/e1xTbLf6JLhwwzeWbdMfWdPfcwg\"",
"id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw"
}
]
}
To extract the JSON data i'm using the a few lines of code and a function in php:
$banner_data = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=brandingSettings&forUsername=pewdiepie&key=AIzaSyDTxvTLWXStUrhzgCDptVUG4dGBCpyL9MY');
$banner_data = json_decode($banner_data, true);
$YTid = $banner_data['items']['id'];
When i :
echo "YouTube Channel Id Of pewdiepie is " . $YTid . ".<br />";
I don't get the channel id? What's my problem?
Items is an array containing one or more objects. So it has to be:
$YTid = $banner_data['items'][0]->id;
This way you grab 'id' from the first item in the items-array.
BTW: learning to debug is crucial to learning to code. If you decode the json and then print the outcome you can see the structure of the array, which could have helped you to find the problem, like:
$banner_data = json_decode($banner_data, true);
var_dump($banner_data);
Try this instead:
$YTid = $banner_data['items'][0]['id'];