I am trying to print out the album information for a certain artist and album using the last.fm api. I have used dump-autoload for the api library (so the classes should be available). In one of my controllers, LastFMController.php, I have the following:
public function some_function() {
$authVars['apiKey'] = '************************';
$auth = new lastfmApiAuth('setsession', $authVars);
$artistName= "Coldplay";
$albumName = "Mylo Xyloto";
$album = Album::getInfo($artistName, $albumName);
echo '<div>';
echo 'Number of Plays: ' . $album->getPlayCount() . ' time(s)<br>';
echo 'Cover: <img src="' . $album->getImage(4) . '"><br>';
echo 'Album URL: ' . $album->getUrl() . '<br>';
echo '</div>';
}
I have a route that runs this code. When I run this, I get the following error:
Class 'Album' not found
Any idea what I'm doing wrong? Thank you.
You you are using this package: https://github.com/fxb/php-last.fm-api
You might have forgotten to autoload api classes:
require __DIR__ . "/src/lastfm.api.php";
Or you can add it to composer.json, as an example:
"autoload": {
"files": [
"/var/www/yourproject/libraries/lastfm.api/src"
],
},
And execute:
composer dump-autoload
EDIT:
You are using one package and the example from another one. There is no Album class in the package you are using, here is a full example of it:
<?php
// Include the API
require '../../lastfmapi/lastfmapi.php';
// Get the session auth data
$file = fopen('../auth.txt', 'r');
// Put the auth data into an array
$authVars = array(
'apiKey' => trim(fgets($file)),
'secret' => trim(fgets($file)),
'username' => trim(fgets($file)),
'sessionKey' => trim(fgets($file)),
'subscriber' => trim(fgets($file))
);
$config = array(
'enabled' => true,
'path' => '../../lastfmapi/',
'cache_length' => 1800
);
// Pass the array to the auth class to eturn a valid auth
$auth = new lastfmApiAuth('setsession', $authVars);
// Call for the album package class with auth data
$apiClass = new lastfmApi();
$albumClass = $apiClass->getPackage($auth, 'album', $config);
// Setup the variables
$methodVars = array(
'artist' => 'Green day',
'album' => 'Dookie'
);
if ( $album = $albumClass->getInfo($methodVars) ) {
// Success
echo '<b>Data Returned</b>';
echo '<pre>';
print_r($album);
echo '</pre>';
}
else {
// Error
die('<b>Error '.$albumClass->error['code'].' - </b><i>'.$albumClass->error['desc'].'</i>');
}
?>
Related
I'm sending data with Laravel HTTP client to a practice PHP API. my Laravel code:
$p = 'img.jpg';
$path = storage_path('app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $p);
$response = Http::attach('new_file', file_get_contents($path), 'new_file.jpg')->post('http://localhost/imageresizer/service.php',
['sizes[0][new_width]' => 400, 'sizes[0][new_height]' => 200, 'sizes[1][new_width]' => 300, 'sizes[1][new_height]' => 500]);
$json = json_decode($response);
dd($json);
and i have this in my php scripts:
$response = [
'status' => http_response_code(),
'zip name' => basename($zipname),
'link' => 'http://localhost/imageresizer/zip/' . basename($zipname)
];
header("Content-Type: application/json");
echo json_encode($response);
I want to access each value from $response keys in my PHP API but i fail. How can i do it? (the current result for dd($json); is null). I want to do something like $json->$response['status']; in my Laravel app.
You have to use response() function to send back the requested data;
return response()->json(['data' => $dataToBeSent], 200);
You can use above code at end of that function.
You can see full detail in this official document
I am working on this legacy system that needs to maintain its SOAP service, and I am currently trying to integrate it with codeigniter, keeps giving me an error XML error parsing SOAP payload on line 70: Reserved XML Name. I have tried the trim solution that someone mention and that did not work. It does not give me this error with normal arrays. Only multidimensional arrays. Any advice would be appreviated
<?php
class Employee_Trainings_Soap extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->library("Soap_lib");
$this->nusoap_server = new soap_server();
}
public function employee_detail() {
$namespace = 'http://localhost/employee_trainings_soap/employee_detail?wsdl';
$this->nusoap_server->debug_flag = true;
$this->nusoap_server->configureWSDL('EmployeeTrainings', $namespace);
$this->nusoap_server->wsdl->schemaTargetNamespace = $namespace;
$this->nusoap_server->wsdl->addComplexType('response', 'complexType', 'struct', 'all', '', array(
"validOPIN" => array(
"name" => "valid_OPIN",
"type" => "xsd:string"
),
"message" => array(
"name" => "message",
"type" => "xsd:string"
)
));
$this->nusoap_server->wsdl->addComplexType('responses', 'complexType', 'array', '', 'SOAP-ENC:Array', array(), array(
array(
"ref" => "SOAP-ENC:arrayType",
"wsdl:arrayType" => "tns:response[]"
)),
"tns:response"
);
$this->nusoap_server->register('getEmployeeTrainings', array("id" => "xsd:string"), array('test'=>'tns:responses'),
$namespace, $namespace."#getEmployeeTrainings", "rpc", "encoded",
'Use this service to list notaries connected to the signed-in title company.'
);
function getEmployeeTrainings($id) {
$data = array();
$data[] = array('valid_OPIN'=>'test','message'=>'test2');
$data[] = array('valid_OPIN'=>'test','message'=>'test2');
//$data = array('valid_OPIN'=>'test','message'=>'test2');
return array('test'=>$data);
}
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
$this->nusoap_server->service($POST_DATA);
}
function live_client_test() {
$this->soapclient = new nusoap_client('http://localhost/employee_trainings_soap/employee_detail');
$err = $this->soapclient->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
$result = $this->soapclient->call('getEmployeeTrainings', array('id' => 'test'));
if ($this->soapclient->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
$err = $this->soapclient->getError();
if ($err) {
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
}
}
So I have found the issue, this may not be the only solution, it is the solution that we found that worked for us. We had to take the SOAP Service out of Code Igniter for it to work. The moment that we took the service outside of Code Igniter, it worked. This may be a bug with code igniter or it could have been with the way we were using it, but as a quick solution it worked. Additionally, we also found it worked better on a Linux dev box compared to an XAMPP dev box. I hope this helps anyone else that might have the same issue.
I have been trying to post to an event that has already been created in a mySQL database and use facebook's graph api to post it to a group page. I am able to post an array created right in the code, but I would like to post an array that I am pulling in from a POST command. Here is what I have.
public function get_event()
{
require_once 'application/php-sdk/facebook.php';
$config = array(
'appId' => '1407968509465242',
'secret' => '***********************',
'cookie' => false,
'fileUpload' => true
);
$id = $_POST['eventsDrp'];
$this->load->model('mdl_facebook_event');
$output = $this->mdl_facebook_event->get_event($id);
print_r ($output);
$facebook = new Facebook($config);
// Set the current access token to be a long-lived token.
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken();
$page_id = '594922100555123';
$page_access_token = '*******************';
// Declare the variables we'll use to demonstrate
// the new event-management APIs
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = '2012-04-24T22:01:00+0000';
$event_privacy = "SECRET"; // We'll make it secret so we don't annoy folks.
// We'll create an event in this example.
// We'll need create_event permission for this.
$params = array(
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'access_token' => $page_access_token,
'page_id' => $page_id //where $page_id is the ID of the page you are managing
);
// Create an event
$ret_obj = $facebook->api("/$page_id/events", 'POST', $output);
if(isset($ret_obj['id'])) {
// Success
$event_id = $ret_obj['id'];
echo ('Event ID: ' . $event_id);
} else {
echo ("Couldn't create event.");
}
// Convenience method to print simple pre-formatted text.
function printMsg($msg) {
echo "<pre>$msg</pre>";
}
I am trying to post the array from $output. I have tried to post from $params and everything works fine. When I try and post from $output I get Fatal error:
Uncaught OAuthException: Invalid token: "594922100555123". An ID has already been specified.
This is the simple code I`m using to upload an image in my rackspace account with PHP :
<?php
$api_username = 'lolcat';
$api_key = 'sexyapi';
require 'cloudfiles.php';
$auth = new CF_Authentication($api_username, $api_key);
$auth->authenticate();
$connection = new CF_Connection($auth);
$images = $connection->create_container("pitch");
$url = $images->make_public();
echo 'The url is '.$url;
$file = 'sherlock.jpg';
$img = $images->create_object($file);
$img->load_from_filename($file)
?>
Also everytime it gives diffrent errors. Like:
"Strict standards: Only variables should be passed by reference in C:\wamp\www\cloudfiles.php on line 1969 "
" Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\cloudfiles_http.php on line 1249"
A sample of errors (imgur image)
Please help I`ve been trying this simple thing for 2 hours now.
Php-cloudfiles bindings are deprecated. I suggest you to give php-opencloud a try. I shouldn't be hard to port your code. Here's a quick example:
<?php
require 'vendor/autoload.php';
use OpenCloud\Rackspace;
$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array(
'username' => 'foo',
'apiKey' => 'bar'
));
$service = $client->objectStoreService('cloudFiles', 'DFW');
$container = $service->createContainer('pitch');
$container->enableCdn();
$cdn = $container->getCdn();
//Print "Container SSL URL: " . serialize($cdn);
$files = array(
array(
'name' => 'file_1.txt',
'body' => fopen('files/file_1.txt', 'r+')
)
);
$container->uploadObjects($files);
You can find php-opencloud docs at: https://github.com/rackspace/php-opencloud/blob/master/docs/getting-started.md
pretty new with the aws sdk, looking to start. i've installed the sdk and everything but how do I start the ec2 instances using the php sdk? Some code samples would really be useful.
Here is a basic example of starting a machine from a defined AMI:
$image_id = 'ami-3d4ff254'; //Ubuntu 12.04
$min = 1; //the minimum number of instances to start
$max = 1; //the maximum number of instances to start
$options = array(
'SecurityGroupId' => 'default', //replace with your security group id
'InstanceType' => 't1.micro',
'KeyName' => 'keypair', //the name of your keypair for auth
'InstanceInitiatedShutdownBehavior' => 'terminate' //terminate on shutdown
);
require_once('AWSSDKforPHP/sdk.class.php');
$ec2 = new AmazonEC2();
$response = $ec2->run_instances($image_id, $min, $max, $options);
if(!$response->isOK()){
echo "Start failed\n";
}
This is assuming you have your AWS credentials setup properly ... Hopefully this gets you pointed in the right direction ...
Here is a more detailed script if you are interested:
// Sleep time to allow EC2 instance to start up
$sleeptime = 15;
$username = "ec2-user";
// For AWS PHP SDK
putenv('HOME=/home/ec2-user/');
require_once 'AWSSDKforPHP/sdk.class.php';
// Get data from HTTP POST
$ami = $_POST['amis'];
$instancetype = $_POST['instancetype'];
$keyname = $_POST['key'];
$securitygroup = $_POST['securitygroups'];
// Instantiate the AmazonEC2 class
$ec2 = new AmazonEC2();
// Boot an instance of the image
$response = $ec2->run_instances($ami, 1, 1, array(
'KeyName' => $keyname,
'InstanceType' => $instancetype,
'SecurityGroupId' => $securitygroup,
));
if (!($response->isOK())) {
echo "<p class='error'>ERROR! Could not create new instance!</p>";
return;
}
$instance = $response->body->instancesSet->item->instanceId;
$message = "<p>Your instance has been successfully created.</p>";
$message .= ("<p>Instance ID is: <b>$instance</b></p>");
// Give instance some time to start up
sleep ($sleeptime);
// Get the hostname from a call to the DescribeImages operation.
$response = $ec2->describe_instances(array(
'Filter' => array(
array('Name' => 'instance-id', 'Value' => "$instance"),
)
));
if (!($response->isOK())) {
echo "<p class='error'>ERROR! Could not retrieve hostname for instance!</p>";
return;
}
$hostname = $response->body->reservationSet->item->instancesSet->item->dnsName;
// Output the message
$message .= "<p>Your instance hostname is: <b>$hostname</b></p>";
$message .= "<p>You can connect to your instance using this command:<br>" .
"<b>ssh -i $keyname.pem $username#" . $hostname . "</b></p>";
echo $message;
Pretty much the same as #dleiftah's, except that it outputs the hostname of the new instance upon completion.