Skip to content

Instantly share code, notes, and snippets.

@blainelang
Last active July 17, 2017 12:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save blainelang/46353455dbaf53499c58 to your computer and use it in GitHub Desktop.
Save blainelang/46353455dbaf53499c58 to your computer and use it in GitHub Desktop.
Drupal 8 standalone PHP script using Guzzle to request a node with a JSON response and HTML response.
<?php
/* Script located in the docroot for your Drupal 8 site */
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;
$autoloader = require_once __DIR__ . '/core/vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
echo '<h1>RESTful request to get a json response for node 1</h1>';
$request = $client->createRequest('GET', 'http://localhost/d8test2/node/1');
// Set the Accept header for the D8 JSON representation
$request->setHeader('Accept', 'application/hal+json');
$response = $client->send($request);
$json = $response->json();
echo '<pre>' . var_dump($json) . '</pre><hr>';
// Now display just the node body value
echo '<h1>Node 1 body value</h1>';
print $json['body'][0]['value'];
echo '<h1>Retrieve the complete site</h1>';
$response = $client->get('http://localhost/d8test2/node/1');
$body = $response->getBody();
// By default if the response is large, Guzzle will save the body in a temp file
while (!$body->eof()) {
echo $body->read(1024);
}
@jbfelix
Copy link

jbfelix commented Apr 28, 2017

Then how to fix this script ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment