Need help: Reading my Google spreadsheet, keeping it private - php

Getting super frustrated trying to get this working. Basically this is for a site (x10hosting.com) where I can't include the zend gdata framework, so I'm trying to use the Google Data API with php cURL to access it. The most I've been able to do is return a list of the supplied usernames worksheets, using this script:
<?php
// Construct an HTTP POST request
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "", //username
"Passwd" => '', //password
"service" => "writely",
"source" => "your application name"
);
// Initialize the curl object
$curl = curl_init($clientlogin_url);
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute
$response = curl_exec($curl);
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
echo "The auth string is: ".$auth;
// Include the Auth string in the headers
// Together with the API version being used
$headers = array(
"Authorization: GoogleLogin auth=".$auth,
"GData-Version: 3.0",
);
// Make the request
$key = ;
curl_setopt($curl, CURLOPT_URL, "https://spreadsheets1.google.com/ccc?key=$key");
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
$response = curl_exec($curl);
curl_close($curl);
var_dump($response);
// Parse the response
$response = simplexml_load_string($response);
// Output data
foreach($response->entry as $file)
{
echo "File: " . $file->title . "<br />";
echo "Type: " . $file->content["type"] . "<br />";
echo "Author: " . $file->author->name . "<br /><br />";
}
?>
But I can't figure out a way to use this to access one specific worksheet. Please help, this is driving me nuts.
EDIT: Following DASPRiD's advice gives me this error->
Notice:
Zend_Loader::Zend_Loader::registerAutoload is deprecated as of 1.8.0 and will be
removed with 2.0.0; use
Zend_Loader_Autoloader instead in
/home/c3webdev/public_html/library/Zend/Loader.php
on line 266
Warning:
require_once(Zend/Loader/Autoloader.php)
[function.require-once]: failed to
open stream: No such file or directory
in
/home/c3webdev/public_html/library/Zend/Loader.php
on line 267
Fatal error: require_once()
[function.require]: Failed opening
required 'Zend/Loader/Autoloader.php'
(include_path='/home/c3webdev/public_html/library:.:/usr/lib/php:/usr/local/lib/php')
in
/home/c3webdev/public_html/library/Zend/Loader.php
on line 267

A query to the following URL should list you all worksheets of a specific spreadsheet:
http://spreadsheets.google.com/feeds/worksheets/**spreadsheetKey**/private/full
To install and use Zend_Gdata, do the following:
Download the last package (http://framework.zend.com/releases/ZendGdata-1.10.7/ZendGdata-1.10.7.tar.gz) from the Zend Framework website. Now let's assume the following directors structure:
/index.php (your main file)
/library/Zend (extract the library/Zend folder in here)
Now in your index.php, do the following:
set_include_path(
dirname(__FILE__) . '/library'
. PATH_SEPARATOR . get_include_path()
);
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
Now you can simply follow the manual (http://framework.zend.com/manual/en/zend.gdata.spreadsheets.html). Interesting for you may be the topics "Get a List of Spreadsheets" for creating the service instance and "Get a List of Worksheets" to fetch all worksheets of a specific spreadsheet.
Update:
It looks like the Zend_Gdata package is not properly packaged. I will note that to get the package fixed. In the meantime, I suggest you to download the complete Zend Framework package. To use the autoloader in 1.8 correctly, do the following instead:
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();

Once you get the list of supplied worksheets for that user you can parse through to get the data (thats what you want right? the worksheet data?)
As mentioned above this is how you get the spreadsheets available
http://spreadsheets.google.com/feeds/worksheets/<spreadsheet-key>/private/full
Then from there you can get the url to a specific spreadsheet and then from there you can get the data from that
List returns the data with appropriate headings
https://spreadsheets.google.com/feeds/list/<spreadsheet-key>/<worksheet-id>/private/basic
Cells returns it with defined cells (A1, C23 etc.)
https://spreadsheets.google.com/feeds/cells/0<spreadsheet-key>/<worksheet-id>/private/basic
Here is more info on the google spreadsheets api reference

For a really easy alternative solution without Zend and without Google API this may also help.
You can publish your Google Spreadsheet as csv on the web (with a private URL) and simply access it by fopen/fgetcsv:
https://stackoverflow.com/a/18106727/1300348
Please be aware there is no authentication... so whoever has your url has your data, hence this might not be the right solution for files where there are passwords included.
But maybe it helps someone with a similar problem.

Related

Filemaker api retruns 958 error code in php

I am trying to access FileMaker by using curl PHP. here I am not using filmmaker PHP class. I am importing the records from the filmmaker into the Prestashop site. when admin delete the product in the Prestashop its also deleted in the FileMaker database
$nome = 'http://ipaddress:port/fmi/xml/FMPXMLRESULT.xml?-db=tablename&-lay=export&recordid=$recordid&-delete';
$cURL = curl_init($nome);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_FAILONERROR, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, $header_fields);
$response = curl_exec($cURL);
if ($cURL_err = curl_errno($cURL)) {
die(__FILE__ . "(" . __LINE__ . "): Communication Error: (' . $cURL_err . ')" .
curl_error($cURL));
}
curl_close($cURL);
//Removed the Headers.
when I am executing the code filmmaker return error code 958.
after some analyze.
if we want edit,delete,update the record in the filemaker.we must use the -recid.
i made mistake on API
$nome = 'http://ipaddress:port/fmi/xml/FMPXMLRESULT.xml?-db=tablename&-lay=export&recordid=$recordid&-delete';
it should be
$nome = 'http://ipaddress:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=export&-recid=$recordid&-delete';
after changed its working correctly.Here I attached some example API for getting records and update the records.
GET all records
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=layout&-findall
Get range of records
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=Magazzino&-lay=export&-max=100&-findall
Get specific Record
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=export&fieldname=field_value&-find
Insert New
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=export&fieldname=field_value&-new
edit record
http://ip_address:port/fmi/xml/FMPXMLRESULT.xml?-db=database&-lay=export&-recid=record_id&-edit
NOTE: Two way to access filmmaker database 1.using FileMaker class.2.using API

How to decode Json data from php file into another php file?

I am new in Creating API`s and I have created 2 files.php
1- API_ReadAll.php ( Its an API code that after execution will return Json Result)
Example Execute the below link:
http://localhost:8080/To%20work%20on/API_FUNCTIONS/API_ReadAll.php
Output:
Status Data Records:
[
{
STATUS_ID: "14",
STATUS_CODE: "AP 2013",
STATUS_DESCRIPTION: "Amazing wheel"
}, {
STATUS_ID: "13",
STATUS_CODE: "AP55.0",
STATUS_DESCRIPTION: "A23 Powder"
}, {
STATUS_ID: "16",
STATUS_CODE: "AP525.0",
STATUS_DESCRIPTION: "Power Drink"
}
]
2- Index.php ( Its an php file consist of HTML elements and table to display the data retrieved from the the page above)
I have tried to do the below:
// path to your JSON file
$url = 'http://localhost:8080/To%20work%20on/API_FUNCTIONS/API_ReadAll.php';
$json = file_get_contents($url);
$data = json_decode($json,true);
echo $data->STATUS_ID;
foreach($data As $display){
echo $display->STATUS_ID."<br>";
echo $display->STATUS_CODE."<br>";
echo $display->STATUS_DESCRIPTION."<br>";
}
Output:
Warning: file_get_contents( http://localhost:8080/To%20work%20on/API_FUNCTIONS/API_ReadAll.php): failed to open stream: No such file or directory in C:\xampp\htdocs\To work on\Temp-Builder\SEED_STATUS.PHP on line 122
Notice: Trying to get property 'STATUS_ID' of non-object in C:\xampp\htdocs\To work on\Temp-Builder\SEED_STATUS.PHP on line 125
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\To work on\Temp-Builder\SEED_STATUS.PHP on line 125
Question:
How can I get and fetch the above Json inside the Index.php.
I'd first of all recommend you to read through the following guide create simple rest api with php (or any other tutorial of your choice), to get into the field of REST Apis with php.
Rather than handling api endpoints as file, you can use curl to perform a request against them. The result of that request can then be decoded to json with php's build in json_decode function.
To get you a starting point, I applied your approach to the curl sample found on php.net:
// define api endpoint
$url = 'http://localhost:8080/To%20work%20on/API_FUNCTIONS/API_ReadAll.php';
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$json_obj = json_decode($output)
I also noticed, that you're passing "true" as second parameter to json_decode(). That way you will receive an associative array rather than an object. But in your example you're treating it as an object.
Also be aware of the fact that localhost is only accessable within your local network. So the community here cannot acess your example if that was your intension.
Good luck
-------------------------------------------------------------------------
Thank you for your time:
Regarding the link you provided to me to learn more about how to build the API. I did learn and build my API`s from that link and I successfully achieved what I am looking for.
Second about the code the comment of the link yes sure it will only have access from local serve, and I just posted like that trying to figure if this was a right way or not.
Regarding the code, I just tried your`s and still not working showing the following error:
Notice: Trying to get property 'STATUS_CODE' of non-object in C:\xampp\htdocs\To work on\Temp-Builder\INDEX.PHP....
Code:
// define api endpoint
$url = 'http://localhost:8080/To%20work%20on/Temp-Builder/API_FUNCTIONS/API_ReadAllSeed_Status.php';
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$json_obj = json_decode($output);
foreach ($json_obj as $display){
echo $display->STATUS_ID."<br>";
echo $display->STATUS_CODE."<br>";
echo $display->STATUS_DESCRIPTION."<br>";
}

VIMEO (Pro) get JSON response help (PHP/CURL)

I have a Vimeo PRO account.
I have protected videos uploaded.
Videos are also set to ONLY be embeddable on my domains (set in the video settings)
I am -not- grasping how to use their examples (sorry, for me the examples do not include real working samples for me,..or at least how to implement them to understand.. so I'm hoping to get some help)
Not clear on all the OAuth2, Oembed... authentication stuff either.. which I believe is where my problem lies.
I was following this gitHub example:
https://github.com/vimeo/vimeo-api-examples/blob/master/oembed/php-example.php
(looks to be pretty old?)
I'm looking to get JSON data returned for a video when an ID is passed along.
I was/am under the impression that I need to 'authenticate' before I can get my response/return data?
Is this best done in the CURL header or something?
Can someone guide me a bit more? (shouldnt be this hard!) haha..
Here is my code:
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
//JSON url
//$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
//this fixes the cURL approach
$json_url = $video_endpoint . rawurlencode($video_url);
// Curl helper function
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization : bearer xxxxxx'));
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
$vimeoJSON = json_decode((curl_get($json_url)));
var_dump($vimeoJSON);
And I get this response:
object(stdClass)#1 (1) { ["error"]=> string(52) "You must provide a valid authenticated access token." }
questions are:
1.) Is this even a valid approach? (assuming I just need to append some lines of code to the CURL header to send my auth over before getting a response?)
2.) How do I update my CURL snippet to work with VIEMO authentication?
I'm trying to keep this as CLEAN/SIMPLE as I can (for the JSON call/return portion)..
Any guidance is appreciated.
Thanks
update:
this code does NOT work:
$access_token = 'xxx';
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $json_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The video I want to use is located here:
https://vimeo.com/171811266/5822169b48
IT IS A PRIVATE VIDEO. (not sure you'll be able to see it)..
When I use the latest version of the code posted above.. I get this response:
{"error":"The requested video could not be found"}
Is this because its a PRIVATE video?
(actually I just set the video to be able to be viewed by anyone.. and I still got the same error/response) (not found)
If so.. what is the fix to use MY videos.. that are set to private... but use them on my site/domain still?
===========================================================================
FINAL UPDATE:
Trying to use the code in the readme example:
https://github.com/vimeo/vimeo.php
Trying to use (un-successfully) the LIB #Dashron pointed me too.. I cant even seem to get the basics to work from the GIT Page:
Code:
//project vars
$client_id = 'xxxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$redirect_uri = 'http://domain.com/file.php'; //where do I redirect them back to? the page where I have the embeded video at?
// scope is an array of permissions your token needs to access. You can read more at https://developer.vimeo.com/api/authentication#scopes
$scopes = Array('public', 'private');
$state = 'Ldhg0478y';
require("Vimeo/autoload.php");
$lib = new Vimeo\Vimeo($client_id, $client_secret);
// build a link to Vimeo so your users can authorize your app. //whatever that means and is for?
$url = $lib->buildAuthorizationEndpoint($redirect_uri, $scopes, $state);
// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);
// usable access token
var_dump($token['body']['access_token']);
// accepted scopes
var_dump($token['body']['scope']);
// use the token
$lib->setToken($token['body']['access_token']);
I get this error message:
Parse error: syntax error, unexpected Fatal error: Class 'Vimeo\Vimeo' not found in /usr/www/users/aaemorg/aaem.org/video/vimeo_lib.php
Seems like its not creating instantiating my $lib object/class??
(I know I'm not great at high level PHP class/code... but this absurdly hard just to get a JSON response for video I own to embed (again) on a site I own as well)
Any direction would be appreciated?
======================================================================
Update: "what worked for me"..
I am appreciate the link to the 'official' library.. but the readme examples just didnt work for me...
To keep things nice and easy for others who may be new to the Vimeo API stuff as well.. here is a quick and dirty, simple code sample to get you up and running:
<?
//include offifial library
require("Vimeo/autoload.php");
$client_id = 'xxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$video_id = 'xxx';
$lib = new Vimeo\Vimeo($client_id, $client_secret, $access_token);
$video_response = $lib->request('/videos/'.$video_id);
//dont really need this, but included in case there is some data you need to display
$token_response = $lib->clientCredentials();
//example of parsing out specific data from the array returned
//name/title
echo $video_response['body']['name'] . '<br><br>';
?>
The link you provided is very, very old. It is actually part of a different API, and no longer relevant.
The Library you should be using is located here: https://github.com/vimeo/vimeo.php with many examples in the readme, and the examples directory!
Below code works for me
Please follow this step before
Under video settings : General->privacy, Change Who can watch select box to Anyone.
$url = 'https://api.vimeo.com/videos/388591356';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer 969329f9b5b3882d74d1b39297528242";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$final_result = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result), true );
echo "<pre>";
print_r($final_result);

Including file from main domain on subdomain

I used to include files between sites routinely, until my webhost banned the practice. Now it appears that a recent PHP upgrade also tightened the screws, as I'm getting a "no suitable wrapper could be found" error - and I'm working with LOCAL sites.
Let's start with a website # www.gx.com and a subdomain at subdomain.mysite.com. However, they display locally as two separate websites - mysite.com and subdomain.com.
A page on subdomain.com features the following include request:
require_once($GX_URL."/2b/inc/D/Shared/Body/Bottom/Footer.php
$GX_URL displays as http[://]gx locally and http[://]gx.com online.
How can I modify this include so it works in both situations? I can use the following switch to hold two separate includes, one for online use and the other for local use:
switch(PHP_OS)
{
case 'Linux':
break;
default:
break;
}
I just figured the answer to my first question; I simply mapped out the entire path to the file in the other website on my computer:
/Applications/MAMP/htdocs/gx/2b/inc/D/Shared/Body/Bottom/Footer.php
So I guess I need to do something similar to include a file from my main domain. However, I'll leave this question open in case anyone has a more elegant solution.
I have more you can try one.
Try download html and include to your php page :).
Http Request or CURL request
Use Allow_url_include, example: http://wiki.dreamhost.com/Allow_url_include
Use Object download: http://php.net/manual/de/function.ob-start.php
Example::
1. Curl Download html string
function curl_get($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $this->CURL_UA);
curl_setopt($ch, CURLOPT_REFERER, $this->YT_BASE_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);
return $contents;
}
2. Http send request width file_get_contents
function sendRequest($url, $data = array())
{
$data = http_build_query($data);
$context_options = array('http' => array('method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n",
'content' => $data)
);
$context = stream_context_create($context_options);
$result = file_get_contents($url, false, $context);
return $result;
}
3 Object : http://php.net/manual/de/function.ob-start.php

MongoLab: using php to PUT update using CURL

I have been trying to use MongoLabs api to simplify my life, and for the most part it was working until I tried to push updates to the db using php and curl, anyway no dice. My code is similar to this:
$data_string = json_encode('{"user.userEmail": "USER_EMAIL", "user.pass":"USER_PASS"}');
try {
$ch = curl_init();
//need to create temp file to pass to curl to use PUT
$tempFile = fopen('php://temp/maxmemory:256000', 'w');
if (!$tempFile) {
die('could not open temp memory data');
}
fwrite($tempFile, $data_string);
fseek($tempFile, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
//curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
//curl_setopt($ch, CURLOPT_INFILE, $tempFile); // file pointer
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, DB_API_REQUEST_TIMEOUT);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
)
);
$cache = curl_exec($ch);
curl_close($ch);
} catch (Exception $e) {
return FALSE;
}
My problem seems to be with MongoLab's api. The code bit works perfect except for the fact that labs tells me that the data I am passing is an 'Invalid object{ "user.firstName" :"Pablo","user.newsletter":"true"}: fields stored in the db can't have . in them.'. I have tried passing a file and using the postfields, but neither worked.
When I test it on firefox's Poster plugin the value work fine. If someone out there has a better understanding of MongoLabs stuff I would love some enlightenment. Thanks in advance!
You will need to remove the dots from your field names. You might try going to a schema like this:
{ "user": { "userEmail": "USER_EMAIL", "pass": "USER_PASS" } }
Unfortunately, MongoDB doesn't support using dots in field names. This is because its query language uses the dot as an operator to chain nested field names. If MongoDB were to allow dots in field names dotted queries would become ambiguous without some kind of escaping mechanism.
If this document were legal:
{ "bow.ties": "uncool", "bow": { "ties": "cool" } }
This query would be ambiguous:
{ "bow.ties": "cool" }
Not clear if the document would match or not. Did you mean the field "bow.ties" or the field "ties" nested within the value of field "bow"?
Here's a capture of a mongo shell session demonstrating these ideas.
% mongo
MongoDB shell version: 2.1.1
connecting to: test
> db.stuff.save({"bow.ties":"uncool"})
Wed Jul 18 11:17:59 uncaught exception: can't have . in field names [bow.ties]
> db.stuff.save({"bow":{"ties":"cool"}})
> db.stuff.find({"bow.ties":"cool"})
{ "_id" : ObjectId("5006ff3f1348197bacb458f7"), "bow" : { "ties" : "cool" } }
After sometime working with some other functionality of the project I realized my mistake, and ultimately the source of the confusion.
The curl PUT was intended to send modifier operations to MongoDB. I was sending all my data as JSON and was interrupting decoding it to use in PHP then re-encoding part of it to send back. So the orignal data received looks something like this:
{"userEmail":"p#g.com","pass":"****", "$oid":"5555", "$set":{"user.firstName":"Pablo","user.newsletter":"true"}}
The problem was that I was grabbing the value of "$set" object (in php) and reencoding only the value, {"user.firstName":"Pablo","user.newsletter":"true"} without the operator "$set" and was sending it giving the error. In this case the proper string to send would have been {"$set":{"user.firstName":"Pablo","user.newsletter":"true"}}
While this is a simple mistake I hope that the next time someone does something like this and gets an invalid object error that they are luck enough to find this.

Categories