I'm building a little backoffice for my site and I want to display the webmaster tools data within it, I cannot for the life of me figure this out!
Does anyone have any PHP examples of pulling data from webmaster tools using the API with PHP, I'm not getting the documentation and have found a php class that looks like it no longer works, but is there a working one already out there?
If I had an example to start with I think I could figure out the rest, I have been googling this for a couple of days now and have not had any success.
If I could just pull a list of sites belonging to my account that would be a start!!
For the record I have been digging through the docs at google, but I can't be the first person to have wanted to do this, so there must be people who have got this working!
Any Takers on throwing me a bone?
Iain
Here is a working example to fetch the sites list. I used my xhttp class, which is a PHP cURL wrapper, to hide the finer details in using cURL.
<?php
// Set account login info
$data['post'] = array(
'accountType' => 'HOSTED_OR_GOOGLE', // indicates a Google account
'Email' => '', // full email address
'Passwd' => '',
'service' => 'sitemaps', // Name of the Google service
'source' => 'codecri.me-example-1.0' // Application's name'
);
// POST request
$response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data);
// Extract Auth
preg_match('/Auth=(.+)/', $response['body'], $matches);
$auth = $matches[1];
$data = array();
$data['headers'] = array(
'Authorization' => 'GoogleLogin auth="'.$auth.'"',
);
// GET request
$response = xhttp::fetch('https://www.google.com/webmasters/tools/feeds/sites/', $data);
echo $response['body'];
?>
First thing the script does is to get an Authorization key via Google's ClientLogin. The service name used is sitemaps. You could also use OAuth or Oauth2 or AuthSub.
Next is to fetch the API URL endpoint for getting the sites list and just adding an Authorization header field.
UPDATE: APRIL 20, 2012
CLIENT LOGIN method as illustrated in the above script example won't work anymore because its deprecated by Google. See details here: https://developers.google.com/accounts/docs/AuthForInstalledApps
The best solution would be to use Oauth 2.0 to connect to Google webmaster tools API.
You can use this class to get data: This has been tested, help you to get
TOP_PAGES, TOP_QUERIES,CRAWL_ERRORS, CONTENT_ERRORS,CONTENT_KEYWORDS, INTERNAL_LINKS, EXTERNAL_LINKS, SOCIAL_ACTIVITY
https://github.com/eyecatchup/php-webmaster-tools-downloads
Hope this may help you.
Assuming you have your Application setup correctly, here's an example of the approach I took:
// Authenticate through OAuth 2.0
$credentials = new Google_Auth_AssertionCredentials(
'1111111111-somebigemail#developer.gserviceaccount.com',
[Google_Service_Webmasters::WEBMASTERS_READONLY],
file_get_contents( 'path-to-your-key.p12' )
);
$client = new Google_Client();
$client->setAssertionCredentials( $credentials );
if ( $client->getAuth()->isAccessTokenExpired() ) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Webmasters($client);
// Setup our Search Analytics Query object
$search = new Google_Service_Webmasters_SearchAnalyticsQueryRequest;
$search->setStartDate( date( 'Y-m-d', strtotime( '1 month ago' ) ) );
$search->setEndDate( date( 'Y-m-d', strtotime( 'now' ) ) );
$search->setDimensions( array( 'query' ) );
$search->setRowLimit( 50 );
// Pass our Search Analytics Query object as the second param to our searchanalytics query() method
$results = $service->searchanalytics->query( $url, $search, $options )->getRows();
// Build a CSV
if ( ! empty( $results ) ) {
// Setup our header row
$csv = "Rank,Query,Clicks,Impressions,CTR,Position\r\n";
foreach ( $results as $key => $result ) {
// Columns
$columns = array(
$key + 1,
$result->keys[0],
$result->clicks,
$result->impressions,
round( $result->ctr * 100, 2 ) . '%',
round( $result->position, 1 ),
);
$csv .= '"' . implode( '","', $columns ) . '"' . "\r\n";
}
file_put_contents( dirname( __FILE__ ) . '/data.csv' );
}
I have a full article I just posted on my blog that has an example class I started to write as a wrapper for both Webmaster Tools API and Analytics API. Feel free to use this as a reference:
http://robido.com/php/a-google-webmaster-tools-api-php-example-using-search-analytics-api-to-download-search-analytics-data-as-csv-with-the-new-oauth-2-0-method/
Related
We are using Woocommerce for our ecom website and in order to automatically generate government-approved invoices for customers we use a certified online invoicing software.
I am making an API request to this invoicing software in order to retrieve the generated invoice document from their database, this is the code:
// On Order complete > Get document ID from order > access Moloni invoicing API > get document link GETPDFLINK > Sanitize the string and get Hash > generate the final document link > access it and download the PDF
function download_moloni_document_id( $order_id, $order ) {
// Retreive from the Database table moloni_api the access token from column main_token
global $wpdb;
$table_name = "db_invoicing_api";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name WHERE id = 1" );
foreach ($retrieve_data as $retrieved_data) {
$maintoken = $retrieved_data->main_token;
}
// Get document ID from the order
$documentid = get_post_meta($order->id, '_moloni_sent', true);
// Connect to moloni API and getpdflink
$url = "https://api.moloni.pt/v1/documents/getPDFLink/?access_token=$maintoken";
$postData = array(
'company_id' => '12345',
'document_id' => $documentid );
$arguments = array(
'method' => 'POST',
'headers' => array(
'Content-type: application/x-www-form-urlencoded'
),
'body' => $postData,
);
$response = wp_remote_post( $url, $arguments );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
return "Something went wrong: $error_message";
} else {
echo '<pre>';
var_dump( wp_remote_retrieve_body( $response ) );
echo '</pre>';
// jsondecode the string received by the API to remove backslashes, get and parse the URL and extract the HASH key
$response2 = wp_remote_retrieve_body($response);
parse_str(parse_url(json_decode($response2, true)['url'], PHP_URL_QUERY), $result);
$hash = $result['h'];
// Assemble the Invoice HTML download URL with the Hash and document ID
$fileUrlpdf = "https://www.moloni.pt/downloads/index.php?action=getDownload&h=$hash&d=$documentid&e=$loginmail&i=1&t=n";
$pdforderid = $order->id;
// Save the file with document id name to server location
$saveTopdf = "ftp://myserver/INVOICES/evo-$pdforderid.PDF";
file_put_contents(
$saveTopdf,
file_get_contents($fileUrlpdf)
);
} }
add_action( 'woocommerce_order_status_completed', 'download_moloni_document_id', 20, 2 );
In the end you can see I use
file_put_contents(
$saveTopdf,
file_get_contents($fileUrlpdf) );
in order to visit the link, retrieve the PDF and download it.
This works well then the link is generated successfully and sends to a direct download of the invoice PDF
The problem I have is is, sometimes there is an issue and the invoice PDF is not generated, this makes it so that the final link $fileUrlpdf does not lead to a download but instead to a web page with an error message saying something like "No Documents Found" which leads this code to download a PDF of dozens of pages containing the source code/HTML of that page. This is a problem because the PDFs (invoices) are later automatically printed by our system, so we sometimes end up with hundreds of pages of HTML code instead of the invoices.
I have tried to solve this in the following way through conditions:
to check if the download/PDF file exists
if (file_exists($fileUrlpdf)) {
file_put_contents(
$saveTopdf,
file_get_contents($fileUrlpdf)); }
one that would check the $response array for the error message and not proceed (because
$invalid = 'No Documents Found'; if (strpos($response, $valid) !== false) {echo 'No Documents found'; else { *download the PDF* } }
I have also considered the possibility of
checking if the page $fileUrlpdf would contain "No Documents Found", to not download it but I haven't been able to figure this one out either.
Bear with me as you can see my experience with PHP is limited so I would like to ask, what would be the best practice here? What approach would you suggest?
Thank you very much in advance for the attention and advice.
Either look at using the API to fetch the invoice/document and handle errors that way moloni.pt/dev
Or you could look at checking the Content-Type of the response headers as shown below
get_headers
$fileUrlpdf = "https://www.moloni.pt/downloads/index.php?action=getDownload&h=$hash&d=$documentid&e=$loginmail&i=1&t=n";
$fileHeaders = get_headers($fileUrlpdf, true)
if($fileHeaders['Content-Type'] === 'application/pdf') {
// PDF response
}
I'm new to worpdress and completed a basic development in wordpress course, our final project it's to bring a facebook page data like states and pics, to be displayed in a word press site, to be specific to be listed in a page, I've been researching using facebook developers and found out, tha when querying this url, https://www.facebook.com/feeds/page.php?id=[pageID]&format=json y got the JSON with all de data, also I've tested in http://jsonviewer.net/ and looks good, no I'm stuck in how to make that JSON to be displayed on a page at my site.
Please need some help with this,
You can use a Shortcode for that [fb-page id="ID-NUM"], use the function wp_remote_get() to pull the feed and then convert the returned JSON into array using PHP's json_decode().
add_shortcode( 'fb-page', 'shortcode_so_25919996' );
function shortcode_so_25919996( $atts )
{
if( empty( $atts['id'] ) )
return 'Please, provide an ID';
# Request URL content.
$url = 'https://www.facebook.com/feeds/page.php?id=' . $atts['id'] . '&format=json';
$response = wp_remote_get( $url );
if ( is_wp_error( $response ) )
return 'Error fetching the feed.';
# Response OK. Decode the response body.
$json_to_array = json_decode( wp_remote_retrieve_body( $response ), true );
# Print the array as code block. Use a loop to build the output as HTML string.
return '<pre><code>' . print_r( $json_to_array, true ) . '</code></pre>';
}
Or you can call this same function as:
<?php echo shortcode_so_25919996( array( 'id' => 'ID-NUM' ) ); ?>
I am trying to tweet an image using php. I have read the documentation and followed a some tutorials. I don't have any problem when sending a message; however, it does not work with images. I can not find where my mistake is, can anyone help?? I would deeply appreciate it.
<?php
$comments = $_POST['comment'];
if (isset($_POST['Twitter']))
{
require_once('twitter/codebird-php/src/codebird.php');
\Codebird\Codebird::setConsumerKey("xxxxxx","xxxxxx");
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("xxxxxx", "xxxxxxxxxx");
$params = array(
'status' => $comments,
'media[]' => "/images/image1.jpg"
);
$reply = $cb->statuses_update($params);
echo "You have posted your message succesfully";
}
else{
echo "You havent posted anythingh";
}
?>
You need to supply Twitter the fully qualified URI to your image.
You have the following code:
$params = array(
'status' => $comments,
'media[]' => "/images/image1.jpg"
);
Unfortunately, that's not a complete URL to an image, it's a relative URL. Instead, you need to provide something along the lines of this:
$params = array(
'status' => $comments,
'media[]' => "http://www.example.com/images/image1.jpg"
);
In addition, according to the Twitter API v1 documentation, you need to use statuses/update_with_media instead of statuses/update.
If you are using Twitter API v1, Twitter also recommends using v1.1 instead.
I look for an example of PHP code to retrieve the text of a note on the Evernote server.
So far, I only found trivial examples listing the notebooks, and helping to get authenticated. But all the references are for Java and not for PHP, and nothing lists the notes self.
I understand I have to use the function findNotesMetaData but I don't understand what to specify as fourth argument.
I need some help to get further. I don't know enough Java to understand the equivalent statement in PHP. Thanks in advance.
Pierre
You can't get note contents with findNotesMetaData. Here's simple code snippet for getting notes (also refer to the sample on github to know how to get token with OAuth).
use EDAM\NoteStore\NoteFilter;
use Evernote\Client;
$client = new Client(array(
'token' => $accessToken,
'sandbox' => true
));
$filter = new NoteFilter();
$filter->words = "Evernote";
$notes = $client->getNoteStore()->findNotes($filter, 0, 10);
You can see more details about searching notes here.
On github there is PHP Evernote API SDK
https://github.com/evernote/evernote-sdk-php
Not PHP, but the perl answer for this is as follows:
use strict;
use Net::Evernote::Simple;
my $evernote = Net::Evernote::Simple->new(
# Obtain a developer token from Evernote and put it here
dev_token => 'YOUR DEV TOKEN HERE',
);
warn "Evernote API version out of date!\n" if( ! $evernote->version_check() ); # check if our client API version still works
my $note_store = $evernote->note_store() or die "getting notestore failed: $#";
my $notebooks = $note_store->listNotebooks( $evernote->dev_token() ) or die "oops:$!"; # retrieve all of our notebooks. See https://dev.evernote.com/doc/reference/ for other things you can do.
for my $notebook ( #$notebooks ) {
print "evernote->note_store->listNotebooks: " . $notebook->guid() . "\t" . $notebook->name(), "\n";
$arg{'guid'}=$notebook->guid() if($notebook->name() eq 'Some Notebook Name');
}
my $tags = $note_store->listTags( $evernote->dev_token() ) or die "oops:$!";
for my $s ( #$tags ) {
print "evernote->note_store->listTags: " . $s->guid() . "\t" . $s->name(), "\n";
}
use Data::Dumper; print Data::Dumper->Dump([ $notebooks ],['$notebooks']);
my $srch = Net::Evernote::Simple::EDAMNoteStore::NoteFilter->new() or die "oops:$!";
$srch->notebookGuid( $arg{'guid'} ) or warn "hmm: $!";
# $srch->inactive( 1 ); # set this to go through the trash
print Data::Dumper->Dump([ $srch ],['$srch']);
my $res=Net::Evernote::Simple::EDAMNoteStore::NotesMetadataResultSpec->new();
# $authenticationToken, $filter, $offset, $maxNotes, $resultSpec);
my $sr = $note_store->findNotesMetadata( $evernote->dev_token(), $srch, 0, 99999, $res) or die "oops:$!";
print Data::Dumper->Dump([ $res ],['$res']);
print Data::Dumper->Dump([ $sr ],['$sr']);
#($authenticationToken, $guid, $withContent, $withResourcesData, $withResourcesRecognition, $withResourcesAlternateData);
my $note = $note_store->getNote( $evernote->dev_token(), 'some_note_GUID_here', 1, 1, 1, 1) or die "oops:$!";
print Data::Dumper->Dump([ $note ],['$note']);
my $tags = $note_store->listTags( $evernote->dev_token() ) or die "oops:$!";
print Data::Dumper->Dump([ $tags ],['$tags']);
I'm currently working on a project, where i have to get the status of a packet (sent with DHL). I read about the DHL API, which return an XML, but somehow there are no good examples out there. I have found some code snippets, but i have no clue where to register for API Key's.
Have anyone some links or examples for me?
Best regards,
Lukas
There is also this PHP client that can be used to consume the DHL XML API. It can handle all the different services exposed by DHL.
https://github.com/alfallouji/DHL-API
This client does not rely or depend on any framework and it should be fairly easy to integrate with your own code. You can check the samples folder for example on how to use it.
https://github.com/jklz/DHL-API-Tracking-PHP
It is used to connect into DHL using the XML-PI to track shipments using the Air Way Bill. it can handle a single tracking number or as many as you feed into it (has been tested with 250 and other then taking a little time to run had no problems). automatically takes and breaks the array of tracking numbers into chunks and then sends the request to DHL making sure not to pass the max number that can be tracked per request then returns the results as a array.
Quick and dirty without any third party lib and using official API:
<?php
$mode = 'sandbox'; // sandbox or production
$username = ''; // dhl developer account name, not email
$password = ''; // dhl developer account pass
$appname = 'zt12345'; // sandbox app
$apppass = 'geheim'; // sandbox app
$endpoint = 'https://cig.dhl.de/services/' . $mode . '/rest/sendungsverfolgung';
$payload = simplexml_load_string( '<?xml version="1.0" encoding="UTF-8" standalone="no"?><data appname="' . $appname . '" language-code="de" password="' . $apppass . '" piece-code="" request="d-get-piece-detail"/>' );
$shipmentids = array(
'00340434161094015902' // in sandbox only special numbers are allowed
);
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Authorization: Basic " . base64_encode( "$username:$password" )
)
);
$context = stream_context_create( $opts );
foreach ( $shipmentids as $shipmentid ) {
$payload->attributes()->{'piece-code'} = $shipmentid;
$response = file_get_contents( $endpoint . '?' . http_build_query( array( 'xml' => $payload->saveXML() ) ), false, $context );
$responseXml = simplexml_load_string( $response );
$status = null;
// get last state
foreach ( $responseXml->data->data->data as $event ) {
$status = $event->attributes()->{'event-short-status'};
}
echo "Shipment " . $shipmentid . " is in state: " . $status . "\n";
}
There is a nice blog about this. It is unfortunately in German, but the code that is displayed there should still make sense to you.
Source: https://blog.simlau.net/dhl-tracking-api-php.html
Excerpt:
function dhl_tracking($trackingnumber)
{
$data = '<?xml version="1.0" encoding="ISO-8859-1" ?>';
$data .= '<data appname="nol-public" password="anfang" request="get-status-for-public-user" language-code="de">';
$data .= ' <data piece-code="'.$trackingnumber.'"></data>';
$data .= '</data>';
// URL bauen und File hohlen
$xml = simplexml_load_file(sprintf(
'http://nolp.dhl.de/nextt-online-public/direct/nexttjlibpublicservlet?xml=%s', $data
));
// FALSE, wenn Syntax oder HTTP Error
if ($xml === false) return false;
// Wandelt das SimpleXML Objekt in ein Array um
foreach ($xml->data->data->attributes() as $key => $value) {
$return[$key] = (string) $value;
}
return $return;
}
// Aufruf der Funktion
print_r(dhl_tracking($tracking_number));
This function will give back an array that will contain some tracking information:
Array
(
[status] => Die Sendung wurde erfolgreich zugestellt.
[recipient-id-text] => Nachbar
[product-name] => DHL PAKET
[pan-recipient-name] => SIMON LAUGER
)
(In fact, there is WAY more data in there.)
I hope this will help you in some way.