I am connecting to a API which doesnt really have a lot of documentation: I would like to bind the data returned to a table but at the moment its all not even loading...Im rather new at this... Im just not sure how to actually bind the data...Thanks!
Example response from docs:
{
"service":"1",
"name":"Custom Comments",
"type":"Custom Comments"
}
HTML
<div class="col-sm-9">
<?php $api = new Api(); ?>
<?php $services = $api->services(); # return all services ?>
</div><!-- col-sm-9 -->
API CLASS
<?php
class Api
{
public $api_url = 'http://apiurl'; // API URL
public $api_key = 'key'; // Your API key
public function order($data) { // add order
$post = array_merge(array('key' => $this->api_key, 'action' => 'add'), $data);
return json_decode($this->connect($post));
}
public function status($order_id) { // get order status
return json_decode($this->connect(array(
'key' => $this->api_key,
'action' => 'status',
'id' => $order_id
)));
}
public function services() { // get services
return json_decode($this->connect(array(
'key' => $this->api_key,
'action' => 'services',
)));
}
private function connect($post) {
$_post = Array();
if (is_array($post)) {
foreach ($post as $name => $value) {
$_post[] = $name.'='.urlencode($value);
}
}
$ch = curl_init($this->api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if (is_array($post)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, join('&', $_post));
}
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
$result = curl_exec($ch);
if (curl_errno($ch) != 0 && empty($result)) {
$result = false;
}
curl_close($ch);
return $result;
}
}
Related
I'm trying to add an array of players_id to send to push notification to specific mobiles, but I keep getting the error "Incorrect player_id format in include_player_ids (not a valid UUID)"
if ($cons) {
$dado1 = array();
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado1 = array(
$row['funcionarioId']
);
array_push($dado2, $dado1);
}
//echo json_encode($dado2);
} else {
$dado2 = array();
array_push($dado2, $dado1);
$retornoVazio = array("Retorno" => $dado2);
EnviaEmailComErro($sql, sqlsrv_errors(), "Consulta_NFCe - ConsultaDados");
array_push($dado2, array("Success" => "0", "Error" => "1"));
echo json_encode($retornoVazio);
}
function sendMessage($produto, $mesa, $comanda, $garcom, $dado2)
{
$content = array(
"en" => " Garçom $garcom \n o pedido: $produto está pronto!\n mesa: $mesa \n comanda: $comanda",
);
**That where it should add the IDS**
$fields = array(
'app_id' => "***",
'include_player_ids' => array($dado2),
'channel_for_external_user_ids' => 'push',
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic ***'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($produto, $mesa, $comanda, $garcom, $dado2);
$return["allresponses"] = $response;
$return = json_encode($return);
the variable $fields print
{"app_id":"***",
"include_player_ids":[
[
["2610ec53-"],
["045eac07-"],
["8fb19bd9-"]
]
]"
And $response:
{"errors":["Incorrect player_id format in include_player_ids (not a valid UUID): [[\"2610ec53-\"], [\"045eac07-\"], [\"8fb19bd9-\"]]"]}
"The players ID are complete in the code, but I deleted it."
In the if ($cons) { you are pushing all sorts of stuff into arrays, simplify it to
if ($cons) {
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado2[] = $row['funcionarioId'];
}
} else {
And in the function make this change
'include_player_ids' => $dado2,
I've created a form in Wordpress that posts data to Mailchimp using the Mailchimp API. If I use just a regular form, with an action that goes to the appropriate page, it works fine; all the data imports as expected.
However, I want to do it via an AJAX POST command. I'm sending all the same information as when doing it using a traditional posted form, but it doesn't work. The AJAX success condition triggers to show that the page loaded successfully, so there must be something in that page that isn't working.
Here's my form:
<div class="card full">
<form id="mailchimp_actions" method="post" action="/ajax-curl-actions/">
<select name="action" id="action">
<option>Subscribe</option>
<option>Unsubscribe</option>
<option>Find</option>
</select>
<textarea name="import_data" id="import_data" placeholder="Email Address,First Name,Last Name"></textarea>
<input type="submit">
</form>
</div>
Here's the page it posts to:
<?php
// Template Name: AJAX - cURL actions.
$subscribers = bfm_data_format($_POST);
$final_report = array('successes'=>0,'failures'=>array());
foreach($subscribers as $subscriber) :
$post_data = array('email' => $subscriber[0], 'fname' => $subscriber[1], 'lname' => $subscriber[2]);
$action = $_POST['action'];
if(!bfm_subscriber_exists($subscriber[0]) && $action=='Subscribe') $action = 'Add New Subscriber';
$report = bfm_curl_actions(bfm_list_id(),bfm_api_key(),$post_data,$action);
if($report['success']) :
$final_report['successes']++;
else:
$final_report['failures'][] = $report['error'];
endif;
endforeach;
?>
<h1>Import Completed</h1>
<p><?=$final_report['successes']?> records were imported successfully.</p>
<h2>Failed imports</h2>
<table>
<tr>
<th>Email</th>
<th>Reason</th>
</tr>
<?php foreach($final_report['failures'] as $failure): ?>
<tr>
<td><?=$failure['email']?></td>
<td><?=$failure['message']?></td>
</tr>
<?php endforeach; ?>
</table>
Here are the various functions that make it work:
<?php
function bfm_fudge_timeout(){
$wpmetetxt = "
# WP Maximum Execution Time Exceeded
<IfModule mod_php5.c>
php_value max_execution_time 10000
</IfModule>";
$htaccess = ABSPATH .'/.htaccess';
$contents = #file_get_contents($htaccess);
if(!strpos($htaccess,$wpmetetxt))
file_put_contents($htaccess,$contents.$wpmetetxt);
}
add_action("after_switch_theme", "bfm_fudge_timeout");
// Format data
function bfm_data_format($data) {
$import_data = $data['import_data'];
$import_data_lines = explode("\n",$import_data);
$i=0;
foreach($import_data_lines as $import_data_line) :
$import_data_lines[$i] = explode(',',$import_data_line);
$i++;
endforeach;
return $import_data_lines;
}
// MailChimp data manipulation
function bfm_curl_actions($list_id,$api_key,$post_data,$action) {
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $post_data['email'],
'merge_fields' => array(
'FNAME' => $post_data['fname'],
'LNAME' => $post_data['lname'],
)
);
if($action == 'Subscribe' || $action == 'Add New Subscriber') :
$data['status']='subscribed';
elseif($action == 'Unsubscribe'):
$data['status']='unsubscribed';
endif;
$member_id = md5($post_data['email']);
$json_data = json_encode($data);
$ch = curl_init();
$curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/";
if($action!='Add New Subscriber') $curlopt_url.=$member_id; // Member ID needs to be excluded if adding an entirely new person.
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
if($action == 'Subscribe' || $action == 'Unsubscribe' || $action == 'Update') :
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
endif;
if($action == 'Find'):
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
endif;
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
$status = "undefined";
$msg = "";
$myArray = json_decode($result, true);
foreach($myArray as $key => $value)
{
if( $key == "status" )
{
$status=$value;
}
else if ($key == "title")
{
$msg=$value;
}
}
$email = $post_data['email'];
if($action == 'Subscribe' || $action == 'Add New Subscriber'):
if($status == "subscribed") :
$report = array ('success'=>true,'error'=>'');
else:
$report = array ('success'=>false,'error'=>array('email'=>$email,'message'=>$msg));
endif;
endif;
return $report;
}
function bfm_subscriber_exists($email) {
$api_key = bfm_api_key();
$list_id = bfm_list_id();
$auth = base64_encode( 'user:'.$api_key );
$data = array(
'apikey' => $api_key,
'email_address' => $email,
);
$member_id = md5($email);
$json_data = json_encode($data);
$ch = curl_init();
$curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/$member_id";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = json_decode(curl_exec($ch),true);
if ($result['status']=='404') return false;
return true;
die(' '); // Free up memory.
}
?>
All of the above works. Here's the jQuery I'm trying to use to do the same but via AJAX, and it fails.
// MailChimp Functions
$(document).on("submit","#mailchimp_actions",
function(event) {
event.preventDefault();
var import_data = $('#action').val();
var action = $('#import_data').val();
$.post("/ajax-curl-actions/",
{
import_data: import_data,
action: action
},
function () {
alert("All done!");
}
);
}
);
Solved it! I'd transposed the two variables in the AJAX request:
var import_data = $('#action').val();
var action = $('#import_data').val();
should have been:
var import_data = $('#import_data').val();
var action = $('#action').val();
I came across the project where I need to implement web services protected by NTLM authentication.
I gave it try via PHP SoapClient:
$client = new \SoapClient("http://hostname.com/webservice",
array(
'cache_wsdl' => WSDL_CACHE_NONE,
'login' => "username",
'password' => "password"
));
This throws this error:
PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from
'http://hostname.com/webservice' : failed to load external entity
"http://hostname.com/webservice"
I gave it try via CURL:
curl --ntlm -u username:password "http://hostname.com/webservice" --verbose
It works as expected and returned the correct xml.
But again SoapClient doesn't support NTLM authentication.
Does anyone knows anything about PHP Soap+NTLM?
Thanks in advance
I recently had this problem too.
Here's the solution I found:
Create NTLMStream.php with the following contents:
<?php
/*
* Original https://thomas.rabaix.net/blog/2008/03/using-soap-php-with-ntlm-authentication
* Modified by http://blogs.msdn.com/b/freddyk/archive/2010/01/19/connecting-to-nav-web-services-from-php.aspx:
*/
class NTLMStream
{
private $path;
private $mode;
private $options;
private $opened_path;
private $buffer;
private $pos;
public function stream_open($path, $mode, $options, $opened_path) {
$this->path = $path;
$this->mode = $mode;
$this->options = $options;
$this->opened_path = $opened_path;
$this->createBuffer($path);
return true;
}
public function stream_close() {
curl_close($this->ch);
}
public function stream_read($count) {
if(strlen($this->buffer) == 0) {
return false;
}
$read = substr($this->buffer,$this->pos, $count);
$this->pos += $count;
return $read;
}
public function stream_write($data) {
if(strlen($this->buffer) == 0) {
return false;
}
return true;
}
public function stream_eof() {
return ($this->pos > strlen($this->buffer));
}
public function stream_tell() {
return $this->pos;
}
public function stream_flush() {
$this->buffer = null;
$this->pos = null;
}
public function stream_stat() {
$this->createBuffer($this->path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
public function url_stat($path, $flags) {
$this->createBuffer($path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
private function createBuffer($path) {
if($this->buffer) {
return;
}
$this->ch = curl_init($path);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_USERPWD, USERPWD);
$this->buffer = curl_exec($this->ch);
$this->pos = 0;
}
}
class NTLMSoapClient extends \SoapClient
{
function __doRequest($request, $location, $action, $version, $one_way = 0) {
$headers = array(
'Method: POST',
'Connection: Keep-Alive',
'User-Agent: PHP-SOAP-CURL',
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: "'.$action.'"',
);
$this->__last_request_headers = $headers;
$ch = curl_init($location);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, USERPWD);
$response = curl_exec($ch);
return $response;
}
function __getLastRequestHeaders() {
return implode("\n", $this->__last_request_headers)."\n";
}
}
Then in your test.php
<?php
define('USERPWD', 'domain\username:password');
require_once("NTLMStream.php");
stream_wrapper_unregister("https");
stream_wrapper_register("https", "NTLMStream");
$params = [
'stream_context' => stream_context_create([
'ssl' => [
'ciphers'=>'RC4-SHA',
'verify_peer'=>false,
'verify_peer_name'=>false,
'allow_self_signed'=>true,
]]),
'cache_wsdl' => WSDL_CACHE_NONE,
'soap_version' => SOAP_1_1,
'trace' => 1,
'connection_timeout' => 180,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS
];
$client = new NTLMSoapClient("https://hostname.com/webservice", $params);
$retVal = $client->ReadMultiple(...
...
For http:// instead of https:// substitute:
stream_wrapper_register("http", "NTLMStream")
stream_wrapper_register("https", "NTLMStream")
This library helped me (I use composer):
https://packagist.org/packages/matejsvajger/ntlm-soap-client
$url = 'URL_TO_WEBSERVICE_WSDL';
$config = new matejsvajger\NTLMSoap\Common\NTLMConfig([
'domain' => 'domain',
'username' => 'username',
'password' => 'password'
]);
$client = new matejsvajger\NTLMSoap\Client($url, $config);
$response = $client->ReadMultiple(['filter'=>[], 'setSize'=>1]);
foreach ($response->ReadMultiple_Result->CRMContactlist as $entity) {
print_r($entity);
}
I'm pretty sure that the gd$phoneNumber, gd$city, gd$street and gd$country are not valid. I just can not find out what to call these variables.
All the variables just return NULL. See below for my vardump.
["name"]=> string(0) ""
["email"]=> string(18) "xxxx#xxxxxxx.com"
["phoneNumber"]=> NULL
["city"]=> NULL
["street"]=> NULL
["country"]=> NULL
Also I am only able to retrieve information from the Contacts API when in localhost.
When I am on the xxxxxx.appspot.com website it won't retrieve information but it will show the table headers.
QUESTION
How can I retrieve more things than just the name and email address with the Contacts API?
Main.php
Import google contacts
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Naam </th>
<th>Email </th>
<th>Telefoon </th>
<th>Stad </th>
<th>Adres </th>
<th>Land </th>
</tr>
</thead>
<tbody>
<?php
foreach( $google_contacts as $contacts ){
echo'<tr>';
echo'<td>'. $contacts['name']."</td>";
echo'<td>'. $contacts['email'].'</td>';
echo'<td>'. $contacts['phoneNumber']."</td>";
echo'<td>'. $contacts['city'].'</td>';
echo'<td>'. $contacts['street']."</td>";
echo'<td>'. $contacts['country'].'</td>';
echo'</tr>';
}?>
</tbody>
</table>
Response-callback.php
$test = 'HEY';
require_once 'google-api-php-client-1-master/src/Google/autoload.php';
$google_client_id = 'xxxxxx-xxxxxx.apps.googleusercontent.com';
$google_client_secret = 'xxxxxxx';
$google_redirect_uri = 'http://localhost:9080';
//$google_redirect_uri = 'https://importcontacts-1216.appspot.com';
//setup new google client
$client = new Google_Client();
$client -> setApplicationName('ImportContacts');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.google.com/m8/feeds');
$googleImportUrl = $client -> createAuthUrl();
function curl( $url, $post = "" ){
$curl = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
curl_setopt($curl, CURLOPT_URL, $url);
//The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
//TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
//The number of seconds to wait while trying to connect.
if( $post != "" ){
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
//The contents of the "User-Agent: " header to be used in a HTTP request.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
//To follow any "Location: " header that the server sends as part of the HTTP header.
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
//To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
//The maximum number of seconds to allow cURL functions to execute.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
//To stop cURL from verifying the peer's certificate.
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
//google response with contact. We set a session and redirect back
if( isset( $_GET['code'] ) ){
$auth_code = $_GET["code"];
$_SESSION['google_code'] = $auth_code;
header('Location: ' . $google_redirect_uri);
}
if( isset( $_SESSION['google_code'] ) ){
$auth_code = $_SESSION['google_code'];
$max_results = 200;
$fields = array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach( $fields as $key=>$value ){
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://accounts.google.com/o/oauth2/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
$return = array();
if( !empty( $contacts['feed']['entry'] ) ){
foreach( $contacts['feed']['entry'] as $contact ){
//retrieve Name and email address
$return[] = array(
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
'phoneNumber' => $contact['gd$phoneNumber'][0]['address'],
'city' => $contact['gd$city'][0]['address'],
'street' => $contact['gd$street'][0]['address'],
'country' => $contact['gd$country'][0]['address'],
);
}
}
$google_contacts = $return;
unset( $_SESSION['google_code'] );
}
if( !empty( $contacts['feed']['entry'] ) ){
foreach( $contacts['feed']['entry'] as $contact ){
//retrieve Name and email address
$return[] = array(
'name'=> $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
'phoneNumber' => $contact['gd$phoneNumber'][0]['address'],
'city' => $contact['gd$city'][0]['address'],
'street' => $contact['gd$street'][0]['address'],
'country' => $contact['gd$country'][0]['address'],
'' => $contact['gd$']
);
//retrieve user photo
if( isset( $contact['link'][0]['href'] ) ){
$url = $contact['link'][0]['href'];
$url = $url . '&access_token=' . urlencode($accesstoken);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$image = curl_exec($curl);
curl_close($curl);
}
$return['image'] = $image;
echo '';
}
}
Change your return array to:
$return[] = array (
'firstname'=> $contact['gd$name']['gd$givenName']['$t'],
'lastname'=> $contact['gd$name']['gd$familyName']['$t'],
'email' => $contact['gd$email'][0]['address'],
'phoneNumber' => $contact['gd$phoneNumber'][0]['$t'],
'city' => $contact['gd$structuredPostalAddress'][0]['gd$city']['$t'],
'street' => $contact['gd$structuredPostalAddress'][0]['gd$street']['$t'],
'country' => $contact['gd$structuredPostalAddress'][0]['gd$country']['$t'],
);
I'm a beginner in PHP, so maybe someone could help to fix this ?
My web application is showing Google PageInsights API error..
Here's the code, I tried to change version to /v2/, but it still didn't work..
public function getPageSpeed($domain, $api = "")
{
try
{
$callback_url = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?";
$data = array(
'url' => 'http://' . $domain,
'key' => (empty($api) ? $_SESSION['GOOGLEAPI_SERVERKEY'] : $api),
'fields' => 'score,pageStats(htmlResponseBytes,textResponseBytes,cssResponseBytes,imageResponseBytes,javascriptResponseBytes,flashResponseBytes,otherResponseBytes)'
);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$content = json_decode($curl_response, true);
$response = array(
'status' => 'success',
'data' => array(
'pagespeed_score' => (int)$content['score'],
'pagespeed_stats' => $content['pageStats']
)
);
} else {
$response = array(
'status' => 'error',
'msg' => 'Google API Error. HTTP Code: ' . $curl_response->headers['Status-Code']
);
}
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
<?php
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = #file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
$myKEY = "your_key";
$url = "http://kingsquote.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '<pre>';
print_r(json_decode($results,true));
echo '</pre>';
?>
The code shared by Siren Brown is absolutely correct, except that
while getting the scores we need to send the query parameter &strategy=mobile or &strategy=desktop to get the respective results from Page speed API
$url_mobile = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=mobile';
$url_desktop = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=desktop';