I'm a beginner in using laravel. For my webapp I want to use the Google API PageSpeed. When visiting /pagespeed, it gives me this error: ErrorException (E_NOTICE)
Undefined property: stdClass::$ruleScore
Also I'm not sure if i made a correct return. I just want to show the meassured data on the /pagespeed page.
Couldn't really find an answer for my problem, I hope you can help.
I used the pagespeed.php code from https://gist.github.com/typhonius/6259822/revisions and put this in my PagespeedController:
public function pageSpeed(){
$url = 'https://www.facebook.com';
$key = 'my API key';
// View https://developers.google.com/speed/docs/insights/v1/getting_started#before_starting to get a key
$data = json_decode(file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$url&key=$key"));
$dat = $data->formattedResults->ruleResults;
foreach($dat as $d) {
$name = $d->localizedRuleName;
$score = $d->ruleScore;
print "\nTest: " . $name . "\n";
print "Score: " . $score . "\n";
if ($score != 100) {
if (isset($d->urlBlocks[0]->header->args)) {
$advice_header = replace_placeholders($d->urlBlocks[0]->header->format, $d->urlBlocks[0]->header->args);
}
else {
$advice_header = $d->urlBlocks[0]->header->format;
}
print "Advice: " . $advice_header . "\n";
foreach ($d->urlBlocks[0]->urls as $url) {
$advice = replace_placeholders($url->result->format, $url->result->args);
print $advice . "\n";
}
}
};
function replace_placeholders($format, $args) {
$i = 1;
foreach ($args as $arg) {
$format = str_replace("\$" . $i, "$arg->value", $format);
$i++;
}
return view('pagespeed')->with('format');
}
This is in my views folder: pagespeed.blade.php:
#extends('layouts.app')
#section('content')
<h1>Page Speed</h1>
#endsection
This is my Route in web.php:
Route::get('/pagespeed', 'PagespeedController#pageSpeed');
Change this
$score = $d->ruleScore;
to
$score = $d->score;
Related
In a list of Amazon products that I retrieve by analyzing the WordPress database, I have this code that allows me to get product by product their Amazon information:
function get_product_infos(asin, ext){
$.post(window.location.href, {
activate: 'get-product-informations',
asin: asin,
ext: ext
}, function(data){
//var json = JSON.parse(data);
console.log(data);
/*if(json.response === 'alright'){
var current_asin = json.current_asin;
current_asin = $('#'+current_asin);
var next_asin = current_asin.next().attr('id');
var next_ext = current_asin.next().attr('data-domain-ext');
current_asin.find('td').first().find('.progress').text('ok');
if(typeof next_asin !== typeof undefined && next_asin !== false){
get_product_infos(next_asin, next_ext);
}
}*/
});
}
File called with $.post() to have the product information from Amazon:
<?php
$autorisation = isset($_POST['activate']) ? $_POST['activate'] : '';
$current_asin = isset($_POST['asin']) ? $_POST['asin'] : '';
$current_ext = isset($_POST['ext']) ? $_POST['ext'] : '';
if($autorisation !== 'get-product-informations'){
return;
}
use pa\src\com\amazon\paapi5\v1\api\DefaultApi;
use pa\src\ApiException;
use pa\src\Configuration;
use pa\src\com\amazon\paapi5\v1\GetItemsRequest;
use pa\src\com\amazon\paapi5\v1\GetItemsResource;
use pa\src\com\amazon\paapi5\v1\PartnerType;
use pa\src\com\amazon\paapi5\v1\ProductAdvertisingAPIClientException;
require_once(plugin_dir_url( __FILE__ . '/bundles/admin-pages/tool/crawling-system/pa/vendor/autoload.php' ));
function parseResponse($items){
$mappedResponse = array();
foreach ($items as $item) {
$mappedResponse[$item->getASIN()] = $item;
}
return $mappedResponse;
}
function getItems(){
global $wpdb;
$prefix_table = $wpdb->prefix;
$table_name = $prefix_table.'azon_lc';
$result = ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name) ? $wpdb->get_results("SELECT * FROM $table_name") : '';
$access_key = ($result !== '') ? $result[0]->access_key : '';
$secret_key = ($result !== '') ? $result[0]->secret_key : '';
$associate_tag = ($result !== '') ? $result[0]->associate_tag : '';
$config = new Configuration();
/*
* Add your credentials
* Please add your access key here
*/
$config->setAccessKey($access_key);
# Please add your secret key here
$config->setSecretKey($secret_key);
# Please add your partner tag (store/tracking id) here
$partnerTag = $associate_tag;
/*
* PAAPI host and region to which you want to send request
* For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region
*/
$config->setHost('webservices.amazon.'.$current_ext);
$config->setRegion('us-east-1');
$apiInstance = new DefaultApi(
/*
* If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
* This is optional, `GuzzleHttp\Client` will be used as default.
*/
new pa\vendor\GuzzleHttp\guzzle\src\Client(), $config);
# Choose item id(s)
$itemIds = array($current_asin);
/*
* Choose resources you want from GetItemsResource enum
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-items.html#resources-parameter
*/
$resources = array(
GetItemsResource::ITEM_INFOTITLE,
GetItemsResource::OFFERSLISTINGSPRICE);
# Forming the request
$getItemsRequest = new GetItemsRequest();
$getItemsRequest->setItemIds($itemIds);
$getItemsRequest->setPartnerTag($partnerTag);
$getItemsRequest->setPartnerType(PartnerType::ASSOCIATES);
$getItemsRequest->setResources($resources);
# Validating request
$invalidPropertyList = $getItemsRequest->listInvalidProperties();
$length = count($invalidPropertyList);
if ($length > 0) {
echo "Error forming the request", PHP_EOL;
foreach ($invalidPropertyList as $invalidProperty) {
echo $invalidProperty, PHP_EOL;
}
return;
}
# Sending the request
try {
$getItemsResponse = $apiInstance->getItems($getItemsRequest);
echo 'API called successfully', PHP_EOL;
echo 'Complete Response: ', $getItemsResponse, PHP_EOL;
# Parsing the response
if ($getItemsResponse->getItemsResult() != null) {
echo 'Printing all item information in ItemsResult:', PHP_EOL;
if ($getItemsResponse->getItemsResult()->getItems() != null) {
$responseList = parseResponse($getItemsResponse->getItemsResult()->getItems());
foreach ($itemIds as $itemId) {
echo 'Printing information about the itemId: ', $itemId, PHP_EOL;
$item = $responseList[$itemId];
if ($item != null) {
if ($item->getASIN()) {
echo 'ASIN: ', $item->getASIN(), PHP_EOL;
}
if ($item->getItemInfo() != null and $item->getItemInfo()->getTitle() != null
and $item->getItemInfo()->getTitle()->getDisplayValue() != null) {
echo 'Title: ', $item->getItemInfo()->getTitle()->getDisplayValue(), PHP_EOL;
}
if ($item->getDetailPageURL() != null) {
echo 'Detail Page URL: ', $item->getDetailPageURL(), PHP_EOL;
}
if ($item->getOffers() != null and
$item->getOffers()->getListings() != null
and $item->getOffers()->getListings()[0]->getPrice() != null
and $item->getOffers()->getListings()[0]->getPrice()->getDisplayAmount() != null) {
echo 'Buying price: ', $item->getOffers()->getListings()[0]->getPrice()
->getDisplayAmount(), PHP_EOL;
}
} else {
echo "Item not found, check errors", PHP_EOL;
}
}
}
}
if ($getItemsResponse->getErrors() != null) {
echo PHP_EOL, 'Printing Errors:', PHP_EOL, 'Printing first error object from list of errors', PHP_EOL;
echo 'Error code: ', $getItemsResponse->getErrors()[0]->getCode(), PHP_EOL;
echo 'Error message: ', $getItemsResponse->getErrors()[0]->getMessage(), PHP_EOL;
}
} catch (ApiException $exception) {
echo "Error calling PA-API 5.0!", PHP_EOL;
echo "HTTP Status Code: ", $exception->getCode(), PHP_EOL;
echo "Error Message: ", $exception->getMessage(), PHP_EOL;
if ($exception->getResponseObject() instanceof ProductAdvertisingAPIClientException) {
$errors = $exception->getResponseObject()->getErrors();
foreach ($errors as $error) {
echo "Error Type: ", $error->getCode(), PHP_EOL;
echo "Error Message: ", $error->getMessage(), PHP_EOL;
}
} else {
echo "Error response body: ", $exception->getResponseBody(), PHP_EOL;
}
} catch (Exception $exception) {
echo "Error Message: ", $exception->getMessage(), PHP_EOL;
}
}
getItems();
exit;?>
I tested the file in several ways to understand when there was an error and I determined that by trying to use this code it crashes:
$config = new Configuration();
I would like to determine why the call returns a 500 error? There is obviously something that I do not understand.
I have Yii2 project. And there I also have api written by Symfony.
In Symfony part I have method in the class which send request to Yii controller.
$buzz = $this->container->get('buzz');
$buzz->getClient()->setVerifyHost(false);
$buzz->getClient()->setVerifyPeer(false);
$buzz->getClient()->setTimeOut(false);
$url = $this->container->getParameter('integra_sync_prices');
$sendResult = $buzz->post($url, array('authorization' => $this->container->getParameter('load_token')), array('products' =>
json_encode($productPrices)));
$resultJson = json_decode($sendResult->getContent(), true);
if (isset($resultJson['error']))
throw new \Exception('Site: '.$resultJson['error'], 500);
class IntegraController extends Controller{
public function actionIndex()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$headers = Yii::$app->request->getHeaders();
foreach ($headers as $key => $value) {
if(strtolower(trim($key)) == 'authorization') {
$token = trim($value[0]);
break;
}
}
$products = json_decode(Yii::$app->request->post('products'));
$post_products = Yii::$app->request->post('products');
if('111' == $token) {
if(isset($post_products) && $products) {
foreach ($products as $product) {
echo $product->price." = ".$product->productId."<br>";
Yii::$app->db->createCommand("UPDATE oc_product SET quantity = '" . (int)$product->quantity . "', price = '" . (float)$product->price . "' WHERE product_id = '" . (int)$product->productId . "'")->execute();
}
$json['success'] = 'complete';
} else {
$json['error'] = 'empty data';
}
} else {
$json['error'] = 'authorization error';
}
Yii::$app->controller->enableCsrfValidation = false;
echo json_encode($json);
}
I expect that data in my database will be updated by this controller. But there in nothing changes.
What do I do wrong? Maybe I should send some another headers? Thanks a lot )
I am trying to create a small php script that pulls down a list of all user id's of people that are following/friends with a handle on twitter, for this I am using https://twitteroauth.com
I can get the id's to a file itself when I use either "friends" or "followers" individually, but when I am trying to move this script to a function I get "Fatal error: Call to a member function get() on null" (line 19)
the error is triggered because this line
" $tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
"
is being used inside a function...
I used composer and tried and got it to work outside a function.. the 2 main files are
index.php
#!/usr/bin/php
<?php
require __DIR__ . '/vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
require_once 'config.php';
// Pass in arguments
if (PHP_SAPI === 'cli') {
$type = $argv[1];
$term = $argv[2];
}
else {
$type = $_GET['type'];
$term = $_GET['term'];
}
switch ($type){
case 'timeline':
include 'timeline.php';
break;
case 'followers':
case 'friends':
include 'f.php';
break;
case 'ratelimit':
include 'ratelimit.php';
break;
case 'users_followers':
case 'users_friends':
include 'users.php';
break;
case 'all':
// include 'timeline.php';
include 'f.php';
break;
}
?>
And f.php
<?php
function getFrindsFollowers($term, $type){
// create file to print follwer/friends id's to file
$file = "files/" . $term . '_' . $type . '.csv';
// set empty content to file
$content = null;
// set previous cursor
$previous_cursor = 0;
$next_cursor = -1;
$loop_num = 0;
// While statment for followers or friends calls.
while($next_cursor != $previous_cursor && $loop_num < 15 && $next_cursor != 0){
//use Abraham\TwitterOAuth\TwitterOAuth;
//$twitteroauth = new TwitterOAuth(consumer_key, consumer_secret, oauth_access_token, oauth_access_token_secret);
$tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
// Pause the loop for 16 min after every 15th request
if ($loop_num % 15 == 0 && $loop_num > 15) {
echo "sleep mode";
sleep(960);
echo "sleep mode done";
}
// set cursors
$previous_cursor = $next_cursor;
//echo 'Previous cursor is ' . $previous_cursor;
//echo '\n Next cursor is ' . $next_cursor;
foreach($tweets as $key => $val) {
if($key == "ids"){
//echo $val[0];
foreach($val as $value){
$value . "\n";
$content .= ",\n" . $value;
}
}
if($key == "next_cursor"){
//echo "\n \n";
$next_cursor = $val;
}
}
$loop_num ++;
echo "Type is now " . $type . "\n";
echo "Loop is " . $loop_num . " for " . $type . "\n";
file_put_contents($file, $content);
}
}
getFrindsFollowers($term, $type);
?>
Is most likely a easy fix but would appreciate any guidance on how to use a get request inside a function.
You are having trouble with scope (http://php.net/manual/en/language.variables.scope.php)
If you already have the twitteroauth variable defined outside the function, add this line at the start of it
global $twitteroauth;
This will give you access to the variable inside the function.
Hello I am trying to build my first restful web service and im using the instruction from lorna jane mitchell blog.
If the req comes through this Url : http://localhost:8888/lorna/index.php/tree/getpath?node_id=75
i call the function getpath passing node_id
The function get path looks like this :
class NestedSet
{
public function getPath($id) {
$sql = "SELECT p." . $this->pk . ", p." . $this->name . " FROM ". $this->table . " n, " . $this->table . " p WHERE n.lft BETWEEN p.lft AND p.rgt AND n." . $this->pk ." = " . $id . " ORDER BY p.lft;";
$result = $this->db->query($sql);
if ($result->num_rows == 0) {
return $this->error(1, true);
}
$path = array();
$i = 0;
while ($row = $result->fetch_assoc()) {
$path[$i] = $row;
$i++;
}
return $path;
}
}
Now i want to pass this variable $path to the class JsonView that looks like this :
class JsonView extends ApiView {
public function render($path) {
header('Content-Type: application/json; charset=utf8');
echo json_encode($path);
return true;
}
}
class ApiView {
protected function addCount($data) {
if(!empty($data)) {
// do nothing, this is added earlier
} else {
$data['meta']['count'] = 0;
}
return $data;
}
}
Any Idea on how can I pass the variable $path or any other variable through this JsonView Class.
Thank you very much for your time :)
UPDATE This is the code for creating the nested class object
public function getAction($request) {
$data = $request->parameters;
if(isset($request->url_elements[2])) {
switch ($request->url_elements[2]) {
case 'getpath':
$id = $data['node_id'];
$nested = new NestedSet();
$nested->getPath($id);
$api = new JsonView();
$api->render($path);
break;
default:
# code...
break;
}
} else {
$nested = new NestedSet();
echo $nested->treeAsHtml();
}
}
Just create object of JsonView and then call the function render using that object.
$api = new JsonView;
$api->render($path);
this is my code
<?php
require_once('asana.php');
$asana = new Asana(array('apiKey' => 'XXXXXXXX')); // API Key
$userinfo=$asana->getUserInfo();
if ($asana->responseCode != '200' || is_null($userinfo)) {
echo 'Error while trying to connect to Asana, response code: ' . $asana->responseCode;
return;
}
$resultJson = json_decode($userinfo);
foreach ($resultJson->data as $user) {
echo $user->name . ' (id ' . $user->id . ')' . PHP_EOL;
}
?>
In asana.php
public function getUserInfo($userId = null, array $opts = array()) {
$options = http_build_query($opts);
if (is_null($userId)) {
$userId = 'me';
}
return $this->askAsana($this->userUrl . '/' . $userId . '?' . $options);
}
And I got error like this: Notice: Trying to get property of non-object in C:\wamp\www\pngtest\index.php on line 15
What is the problem? Thanks in advance
$resultJson = json_decode($userinfo);
foreach ($resultJson->data as $user) {
}
You're trying to access $resultJson->data before you know if $resultJson is a valid object or not.
Note that json_decode returns:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
It is possible (likely) that $resultJson is NULL, because it was given invalid JSON data. You should echo $userinfo and determine if it is what you expect.