How to install Google Index API in PHP

5.9k views Asked by At

I'm trying to implement the Google index API with PHP, but I have a blank page error 500.

I believe that I've done all the prerequisite for the Indexing API as mentioned here: https://developers.google.com/search/apis/indexing-api/v3/prereqs#php

Then I have uploaded the code below in this folder /indexapi/index.php

require_once 'indexapi/google-api-php-client/src/Google/autoload.php';

$client = new Google_Client();

// service_account_file.json is the private key that you created for your service account.
$client->setAuthConfig('indexapi/service_account_file.json');
$client->addScope('https://www.googleapis.com/auth/indexing');

// Get a Guzzle HTTP Client
$httpClient = $client->authorize();
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';

// Define contents here. The structure of the content is described in the next step.
$content = '{
  "url": "https://myurl2020.com",
  "type": "URL_UPDATED"
}';

$response = $httpClient->post($endpoint, [ 'body' => $content ]);
$status_code = $response->getStatusCode();

print_r($response);
echo "\n";
echo "$status_code";

During the prerequisite, I've also downloaded the JSON private key which I have saved here /indexapi/service_account_file.json

Then I've downloaded the lastest Google API Client Library for PHP (Version 2.6.0) from here https://github.com/googleapis/google-api-php-client, which I've then uploaded into my /indexapi/ folder.

The only error I have is a blank page error 500, I think that there is an issue with the autoload.php (please don't suggest composer, as I'm using a Chromebook, and I haven't find a way to use composer with a Chromebook yet).

Here is my autoload.php file:

/**
 * THIS FILE IS FOR BACKWARDS COMPATIBLITY ONLY
 *
 * If you were not already including this file in your project, please ignore it
 */

$file = __DIR__ . 'indexapi/google-api-php-client/src/Google/autoload.php';

if (!file_exists($file)) {
  $exception = 'This library must be installed via composer or by downloading the full package.';
  $exception .= ' See the instructions at https://github.com/google/google-api-php-client#installation.';
  throw new Exception($exception);
}

$error = 'google-api-php-client\'s autoloader was moved to vendor/autoload.php in 2.0.0. This ';
$error .= 'redirect will be removed in 2.1. Please adjust your code to use the new location.';
trigger_error($error, E_USER_DEPRECATED);

require_once $file;

Thanks,

2

There are 2 answers

2
jdp On BEST ANSWER

Download a release asset for v2.5.0. It looks like the automation broke for v2.6.0. We will get that fixed this week. Require vendor/autoload.php, not the file under src.

Edit: release assets are now available for v2.6.0.

1
Rahul Joshi On

$url = "https://myurl2020.com"; $content = '{ "url": "'.$url.'", "type": "URL_UPDATED" }';