What is the JSON Data? - php

I coded a script longago which is extremely popular however i am about to role out a update using the clever in-app-auto update feature i coded. Now the question is i have lost the JSON data i was displaying to the code which it then decodes and reads and gets the relevant content.
Here is a snippet:
function check_update(){
$v = isset($_GET['v']) ? $_GET['v']:11;
$reqUrl = "http://myserver.myhost.com/api/update/?" . "v=" . $v;
return json_decode(#file_get_contents($reqUrl));
}
function updatefunction(){
$updateResult = check_update();
print $updateResult->content . "\n\r";
}
echo updatefunction();
I have added the "echo updatefunction();" as a debug test for me to see if it is getting the correct data.
Now my question is what should the $reqUrl be showing for this script to echo some content ?
Thanks

Related

How to use Quick-books online Minor-version >= 4

I have done integration with Quick-Books online using quick-books sdk from this link: https://github.com/consolibyte/quickbooks-php.
Everything works perfectly except one issue.
The issue is, when I retrieve Items from quick-books, it returns "Non Inventory" items as "service".
I have read different topics which state that I will have to shift to minor version 4 to resolve the issue.
But I can't find a way of how I can make my current SDK to use minor version 4 or above.
Any help will be appreciated.
For those who have similar issue, I have found a workaround and sharing it for others to benefit if they want:
open the file quickbook_sdk\QuickBooks\IPP\Service.php
Find the following function protected function _query($Context, $realmID, $query)
Replace the following code
$return = $IPP->IDS($Context, $realmID, null, QuickBooks_IPP_IDS::OPTYPE_QUERY, urlencode($query));
With
$query = urlencode($query);
$query .= "&minorversion=4";
$return = $IPP->IDS($Context, $realmID, null, QuickBooks_IPP_IDS::OPTYPE_QUERY, $query);
Note: I was querying Items, so this workaround may only be beneficial in case of getting data through query.
UPDATE:
if you want to add / update items to QuickBooks online with item type NonInventory, You need to modify the following code in your quickbook_sdk/QuickBooks/IPP.php file.
Find function named function _IDS_v3 and inside that function find the following condition
if ($optype == QuickBooks_IPP_IDS::OPTYPE_ADD or $optype == QuickBooks_IPP_IDS::OPTYPE_MOD)
{
$post = true;
$url = $this->baseURL() . '/company/' . $realm . '/' . strtolower($resource);
$xml = $xml_or_query;
}
Replace it with
if ($optype == QuickBooks_IPP_IDS::OPTYPE_ADD or $optype == QuickBooks_IPP_IDS::OPTYPE_MOD)
{
$post = true;
$url = $this->baseURL() . '/company/' . $realm . '/' . strtolower($resource);
$xml = $xml_or_query;
$url .= "?minorversion=4"; // this is the only addition
}
For those who use the official php sdk from Intuit, in the root folder you'll find the file sdk.config. Edit <minorVersion>3</minorVersion>.
If you go to the official PHP SDK:
https://github.com/intuit/QuickBooks-V3-PHP-SDK
You will see that you can use:
$dataService->setMinorVersion("4");
to set the minor version you want to use before making the HTTP call.

Possible to overide a foreach variable parameter within itself?

I have made a small script which uses the Twitch API. The API only allows a maximum of 100 results per query. I would like to have this query carry on until there are no more results.
My theory behind this, is to run a foreach or while loop and increment the offset by 1 each time.
My problem however, is that I cannot change the foreach parameters within itself.
Is there anyway of executing this efficiently without causing an infinite loop?
Here is my current code:
<?php
$newcurrentFollower = 0;
$offset=0;
$i = 100;
$json = json_decode(file_get_contents("https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=25&offset=".$offset));
foreach ($json->follows as $follow)
{
echo $follow->user->name . ' (' . $newcurrentFollower . ')' . "<br>";
$newcurrentFollower++;
$offset++;
$json = json_decode(file_get_contents("https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=25&offset=".$offset));
}
?>
Using a While loop:
while($i < $total)
{
$json = json_decode(file_get_contents("https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=25&offset=".$offset));
echo $json->follows->user->name . ' (' . $newcurrentFollower . ')' . "<br>";
$newcurrentFollower++;
$offset++;
$i++;
}
Ends up echoing this (No names are successfully being grabbed):
Here is the API part for $json->follows:
https://github.com/justintv/Twitch-API/blob/master/v2_resources/channels.md#get-channelschannelfollows
You can use this:
$offset = 0;
$count = 1;
do {
$response = json_decode(file_get_contents(
'https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=100&offset=' . $offset
));
foreach($response->follows as $follow) {
echo $follow->user->name . ' (' . ($count++) . ')' . "</br>";
}
$offset+=25;
} while (!empty($response->follows));
You want to use a while loop here, not just a foreach. Basically:
while (the HTTP request returns results)
{
foreach ($json->follows as $follow)
{
do stuff
}
increment offset so the next request returns the next one not already processed
}
The trickiest part is going to be getting the while condition right so that it returns false when the request gets no more results, and will depend on what the API actually returns if there are no more results.
Also important, the cleanest way would be to have the HTTP request occur as part of the while condition, but if you need to do some complicated computation of the JSON return to check the condition, you can put an initial HTTP request before the loop, and then do another request at the end of each while loop iteration.
The problem is you're only capturing the key not the value. Place it into a datastructure to access the information.
Honestly I find a recursive function much more effective than a iterative/loop approach then just update a datatable or list before the next call. It's simple, uses cursors, lightweight and does the job. Reusable if you use generics on it too.
This code will be in c#, however I know with minor changes you'll be able to get it working in php with ease.
query = //follower object get request//
private void doProcessFollowers(string query)
{
HTTPParse followerData = new HTTPParse(); //custom json wrapper. using the basic is fine. Careful with your cons though
var newRoot = followerData.createFollowersRoot(query); // generates a class populated by json
if (newRoot[0]._cursor != null)
{
populateUserDataTable(newRoot); //update dataset
doProcessFollowers(newRoot[0]._links.next); //recurse
}
}
Anyway - This just allows you to roll through the cursors without needing to worry about indexes - unless you specifically want them for whatever reason. If you're working with generics you can just reuse this code without issue. Find a generic example below. All you need to do to make it reuseable is pass the correct class within the <> of the method call. Can work for any custom class that you use to parse json data with. Which is basically what the 'createfollowerroot()' is in the above code, except that's hard typed.
Also I know it's in c# and the topic is php, with a few minor changes to syntax you'll get it working easily.
Anyway Hope this helped somebody
Generic example:
public static List<T> rootSerialize<T>(JsonTextReader reader)
{
List<T> outputData = new List<T>();
while (reader.Read())
{
JsonSerializer serializer = new JsonSerializer();
var tempData = serializer.Deserialize<T>(reader);
outputData.Add(tempData);
}
return outputData;
}

Scraping & Returning JSON data php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I currently have a script, Can be found here:
http://ddelay.co.uk/bus/find_services2.php
With the following code:
<?php
include('simple_html_dom.php');
$service = $_GET["stop"];
$debug = $_GET["debug"];
$url = $service;
if($debug === "yes"){
echo "URL IS: " . $url . "\n";
}
$search = array('?', ' ', '.asp&');
$replace = array('&', '+', '.asp?');
$url2 = str_replace($search, $replace, $url);
if($debug === "yes"){
echo "REPLACEMENTS: ". $url2 . "\n";
}
$end = "http://tsy.acislive.com" . $url2 . '&showall=1';
if($debug === "yes"){
echo "FINAL URL: ". $end;
}
$html = file_get_html($end);
$ret = $html-> getElementsByTagName('table');
print($ret);
?>
For example which will pull the table from tsy.acislive.com (example: http://ddelay.co.uk/bus/find_services2.php?stop=/web/public_service_stops.asp?service=22?operatorid=36?systemid=30?goingto=Woodhouse)
I then want to be able to convert this table to JSON data to use in my app. Unfortunately I have tried PHP's function JSON_encode($ret); but unfortunately that failed. Would anybody know of how I can convert this table pulled using Simple-Dom-Parser php into Json Data
If you want to convert to JSON, json_encode is the way you should do it. It's a really easy to use function. If you're having trouble with it, there'll be an underlying reason.
Try these to find out what your data looks like:
var_dump($html);
var_dump($ret);
From the PHP manual, the value passed to json_encode Can be any type except a resource., so if it's failing I can only assume that you aren't passing it the correct data.
Post the results of those var_dump calls and I'll edit this with a solution for you.

How to run a search for any movie using the Rotten Tomatoes API?

Could anyone help me to create search for movies using PHP when connecting to the Rotten Tomatoes API?
On the Rotten Tomatoes site they give you example code how to get content for specific movie like so:
<?php
$apikey = 'insert_your_api_key_here';
$q = urlencode('Toy Story'); // make sure to url encode an query parameters
// construct the query with our apikey and the query we want to make
$endpoint = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=' . $apikey . '&q=' . $q;
// setup curl to make a call to the endpoint
$session = curl_init($endpoint);
// indicates that we want the response back
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// exec curl and get the data back
$data = curl_exec($session);
// remember to close the curl session once we are finished retrieveing the data
curl_close($session);
// decode the json data to make it easier to parse the php
$search_results = json_decode($data);
if ($search_results === NULL) die('Error parsing json');
// play with the data!
$movies = $search_results->movies;
echo '<ul>';
foreach ($movies as $movie) {
echo '<li>' . $movie->title . " (" . $movie->year . ")</li>";
}
echo '</ul>';
?>
I'm an beginner with PHP so an example would be great. I have manage to solve this with JavaScript but the server I have to host the page won't display it because of updates. So now I will have to turn to PHP because it displays the code from above too.
You need to create a form with a text field. Name the field q so it will work with your sample code.
Have the form post to the url of your sample php script.
Remove this line:
$q = urlencode('Toy Story');
Replace it with this:
$q = urlencode($_POST['q']);
That should get you started.
Note that no effort is made to sanitize the $_GET. I am just providing the basics you need to have a search form running based on the example code you posted.
If you do not know how to create a form, here is a link to a tutorial:
http://www.tizag.com/phpT/forms.php

Google Calendar/PHP newb question

I've been scouring around for information through the google Calendar API, the Zend docs, and here, and just about everything I find seems to make assumptions on what I already know about PHP, so I'm just getting more lost. I do have a good deal of programming experience... with... um... a FORTH variant. Anyway! I'm trying to pass the output of a PHP script that can be used to get all of the important data from a calendar event into said FORTH variant. What's driving me up the wall is that I can't figure out how to grab something as simple as the UID of a message. Here's what I'm working with:
function outputCalendar($client)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$eventFeed = $gdataCal->getCalendarEventFeed();
foreach ($eventFeed as $event) {
echo $event->title->text . " (" . $event->id->text . ")\n";
foreach ($event->when as $when) {
echo $when->startTime . "\n";
}
}
}
This is based off the example code they gave me, and instead of formatting with with XML tags like in the example, just puts each on its own new line (which is easier for me to pull into the other language.)
Now, I tried to add echo $when->startTime . "\n"; to the loop, but it just tells me:
Fatal error: Uncaught exception 'Zend_Gdata_App_InvalidArgumentException' with message 'Property uid does not exist' in /var/mucktools/Zend/Gdata/App/Base.php:484
So, obviously, I'm going about grabbing the UID the wrong way. Now, here's the thing. These two lines:
echo $event->title->text . " (" . $event->id->text . ")\n";
echo $when->startTime . "\n";
...are pulling data from the event. However, 'title'. 'text', 'startTime' all look like things pulled out of one's posterior. I know, cognitively, that can't be true. There is a library and an API here. But I want to know where I can find a listing of all the crap I can pull out of $event and what the syntax is to do so. Can anyone help me with this?
And before you ask, yes, I have a very good reason to be grabbing the output of a PHP script and stuffing it into an obscure FORTH variant. And no, there's not another way that won't be more complicated than this one. I've done my homework here.
I'm sure you've read the documentation for Zend Gdata. It tells you that you need to provide getCalendarEventFeed() with a Zend_Gdata_Query object, otherwise I think you just get public data back.
Your code then should look something like this:-
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$user = "user#gmail.com";
$pass = "userpassword";
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$gDataCal = new Zend_Gdata_Calendar($client);
$query = $gDataCal->newEventQuery();
$query->setVisibility('private');
$query->setProjection('full');
$query->setOrderby('starttime');
$query->setFutureevents('true');
$eventFeed = $gDataCal->getCalendarEventFeed($query);
foreach ($eventFeed as $event) {
echo $event->title . " (" . $event->id . ")\n";
foreach($event->when as $when){
echo $when->startTime . "\n";
}
}
Hopefully that should get you started in the right direction.
Also the php_openSSL module has to be enabled in PHP for this to work, but I assume you have that already enabled to get as far as you did.

Categories