I am trying to integrate amazon api into my website, so far I have managed to have it navigate to the correct xml part and store that as an variable however i am now trying to insert this varibable into my mysql database and it is giving me this error
Notice: Undefined variable: sql_select in
Fatal error: Call to a member function query() on a non-object
what am i doing wrong?
Entire Code
define('INCLUDED', 1);
error_reporting(E_ALL);
ini_set("display_errors", 1);
$AWS_ACCESS_KEY_ID = "HIDDENFORPRIVACY";
$AWS_SECRET_ACCESS_KEY = "HIDDENFORPRIVACY";
$base_url = "http://free.apisigning.com/onca/xml?";
$url_params = array('Operation'=>"ItemLookup",'Service'=>"AWSECommerceService",
'AWSAccessKeyId'=>$AWS_ACCESS_KEY_ID,'AssociateTag'=>"HIDDENFORPRIVACY",
'Version'=>"2011-08-01",'Availability'=>"Available",'ItemId'=>"0273702440",
'ItemPage'=>"1",'ResponseGroup'=>"EditorialReview", 'Title'=>"Accounting and Finance for Non-Specialists 5th Edition");
// Add the Timestamp
$url_params['Timestamp'] = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
// Sort the URL parameters
$url_parts = array();
foreach(array_keys($url_params) as $key)
$url_parts[] = $key."=".$url_params[$key];
sort($url_parts);
// Construct the string to sign
//$string_to_sign = "GET\nhttp://free.apisigning.com/".implode("&",$url_parts);
//$string_to_sign = str_replace('+','%20',$string_to_sign);
//$string_to_sign = str_replace(':','%3A',$string_to_sign);
//$string_to_sign = str_replace(';',urlencode(';'),$string_to_sign);
// Sign the request
//$signature = hash_hmac("sha256",$string_to_sign,$AWS_SECRET_ACCESS_KEY,TRUE);
// Base64 encode the signature and make it URL safe
//$signature = base64_encode($signature);
//$signature = str_replace('+','%2B',$signature);
//$signature = str_replace('=','%3D',$signature);
//$signature = str_replace(';',urlencode(';'),$string_to_sign);
$url_string = implode("&",$url_parts);
$url = $base_url.$url_string;
//print $url;
$ch = curl_init(); //this part we set up curl
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$xml_response = curl_exec($ch);
curl_close($ch);
header('Content-type: application/xml'); //specify as xml to not display as one long string
echo $xml_response;
$xml = new SimpleXMLElement($xml_response); //time to echo back the correct piece of data
$editorialReview = $xml->Items->Item->EditorialReviews->EditorialReview->Content;
$variable = '<p>Editorial review: '.html_entity_decode($editorialReview).'</p>'."\n";
echo $variable;
$sql_select = mysql_query("INSERT INTO " . DB_PREFIX . "auctions
(amazon_description) VALUES
('" . $variable . "')");
echo ($sql_select);
this does not send errors, but the mysql database shows no change
The error "Undefined variable" indicates that you have not initialized the object.
From the code you printed it seems that $sql_select should be a string which has the select statement.
So you need to do something like :
$variable = '<p>Editorial review: '.html_entity_decode($editorialReview).'</p>'."\n";
echo $variable;
$sql_select .= "INSERT INTO " . DB_PREFIX . "auctions
(amazon_description) VALUES
('" . $variable . "')";
$DB_object->query($sql_select);
Please post the entire code so that the solution can be accurately found out.
Related
I use below PHP code in Laravel to translate one sentence or paragraph from one input field:
$apiKey = env('GOOGLE_TRANSLATOR_API');
$url = env('GOOGLE_TRANSLATOR_LINK') . $apiKey . '&q=' . rawurlencode($name) . '&target='.$language;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
return $responseDecoded['data']['translations'][0]['translatedText'];
and it works perfectly fine.
But now I have two input fields (name and description) and I want to translate both of those fields using one API call and show the results individually.
EDIT
I have tried to use array in the API request as below:
$apiKey = env('GOOGLE_TRANSLATOR_API');
$url = env('GOOGLE_TRANSLATOR_LINK') . $apiKey . '&q=' . array('sentence one', 'sentence two) . '&target='.$language;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
return $responseDecoded['data']['translations'][0]['translatedText'];
But I get Array to string conversion error.
1Installing the Basic Client Libraries Client library PHP
composer require google/cloud-translate
and in your code
use Google\Cloud\Translate\V3\TranslationServiceClient;
$translationServiceClient = new TranslationServiceClient();
/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $textTwo = 'My name is John':
// $targetLanguage = 'fr'; // your lang
// $projectId = '[Google Cloud Project ID]';
$contents = [$text, $textTwo];
$formattedParent = $translationServiceClient->locationName($projectId, 'global');
try {
$response = $translationServiceClient->translateText(
$contents,
$targetLanguage,
$formattedParent
);
// Display the translation for each input text provided
foreach ($response->getTranslations() as $translation) {
printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
}
} finally {
$translationServiceClient->close();
}
View Code in Github
I wached a youtube video and came across these codes.
my php file index.php
<?php
//initialize session
$ch = curl_init();
//set the URL
$url = "http://localhost:81/data.php"
//set options
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execution
$json=curl_exec($ch);
//close
curl_close($ch);
//decode the json
$json=json_decode($json, true);
//loop through the results
for($i=0;$i<['Metadata']['TotalResults'];$i++){
echo "JSON : <b>First Name = </b>". $json['Result'][$i]["FirstName"]." , <b>Last Name = </b>".$json['Result'][$i]["LastName"];
}
?>
my json file data.php
<?php
//metadata which will contain how many resukts we have
$meta_array['TotalResults'] = 1;
$metadata = '{"Metadata" : ';
$metadata .= json_encode($meta_array). ',';
//the data
$array["FirstName"] = 'Gary';
$array["LastName"] = 'George';
$data[] = $array;
//json encode the array
$json_encoded = utf8_encode(json_encode($data));
echo $metadata . ' "Result" : '.$json_encoded. '}' ;
exit();
?>
I am continuously getting the above mentioned error.
I am new to jason and curl.
please help me to solve my problem.
thanks in advance :)
I can't see any semicolon after the url.
$url = "http://localhost:81/data.php";
^ it is missing
In your code block you are using $i<['Metadata']['TotalResults'] at loop. Here you are missing the variable name that is eventually your array name. An example could be:
$i<$your_array['Metadata']['TotalResults']
To get the search result from google, I used those code. Sometimes it work perfectly but sometimes it don't give any answer. Now don't know what is the problem. I need those result for research purpose so I had to browse for different query
if (isset($_GET['content'])) {
// echo $_GET['content'];
$url_all=NULL;
$visibleurl=NULL;
$title_all=NULL;
$content_all=NULL;
$mainstring=NULL;
$searchTerm=$_GET['content'];
$endpoint = 'web';
$key= 'angelic-bazaar-111103';
$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint;
$args['q'] = $searchTerm;
$args['v'] = '1.0';
$url .= '?'.http_build_query($args, '', '&');
$url .="&rsz=". 8;
$ch = curl_init()or die("Cannot init");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$body = curl_exec($ch)or die("cannot execute");
curl_close($ch);
$json = json_decode($body);
for($x=0;$x<count($json->responseData->results);$x++){
$url_all .="#$*##" . $json->responseData->results[$x]->url;
$visibleurl .="#$*##" . $json->responseData->results[$x]->visibleUrl;
$title_all .="#$*##" . $json->responseData->results[$x]->title;
$content_all .="#$*##" . $json->responseData->results[$x]->content;
}
**EDIT
This Code works well sometimes, other times it doesn't, Is it a problem of google or something else. I get this error
$json->responseData->results for this showing "Trying to get property of non-object in"
I use CURL in php, and I use CURL something like this
$url = "http://exampledomain.com";
$smsURL = $url;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
curl_exec ($curl);
curl_close ($curl);
This is not working, but if I wrote "http://exampledomain.com" in place of "$smsURL" at curl_setopt (); It will work fine. Where is issue in my code? did I miss something?
Original Code
$url = $this->conf['sms_getway_url'];
$url .= '&recipient=' . $_POST['txt_customer_contact_no'];
$url .= '&sender=' . strtoupper($saloon_info['saloon_name']);
$url .= '&is_payor=' . $this->conf['sms_is_payor'];
$url .= '&pay_amount=' . $this->conf['sms_pay_amount'];
$url .= '&token=5ce7467e9ec045cbbac448ba5a422a02';
//$url .= '&customer_num=' . $this->conf['sms_customer_num'] . $saloon_id;
$url .= '&customer_num=' . $this->conf['sms_customer_num'];
$appointment_time = date('H:i', strtotime($app_start_time));
$employee_name = $_POST['hdn_selected_employee_name']; //$value['id_employee'];
//$sms_msg = "Hey. Recalling that I await tomorrow at. " . $appointment_time . " Regards " . $employee_name . ", " . $saloon_name . ". ";
$sms_msg = t('msg_sms_book_appointment', array('%emp_name' => $employee_name, '%saloon_name' => $_POST['hdn_selected_saloon_name'], '%time' => $appointment_time));
$url .= '&sms_msg=' . $sms_msg;
$smsURL = $url;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
curl_exec ($curl);
curl_close ($curl);
Thanks
You compose the URL from pieces but you don't encode the values properly. There are characters that have special meaning in URLs (/, ?, &, =, %, , + and a few more). They have to be encoded when they appear in the values from the query string, in order to retain their literal meaning.
PHP helps you for this goal with function urlencode() that can be used to encode each value individually when you create a query string. Something like this:
$url = $this->conf['sms_getway_url'];
$url .= '&recipient=' . urlencode($_POST['txt_customer_contact_no']);
$url .= '&sender=' . urlencode(strtoupper($saloon_info['saloon_name']));
...
But, because this is a tedious work, it also provides an easier method. Put all the values you need into an array, using the names of the variables as keys, then pass the array to function http_build_query(). There is no need to call urlencode() any more; http_build_query() takes care of it. Also it puts ampersands (&) between the variables and equals (=) where they belong.
The code is like this:
$url = $this->conf['sms_getway_url'];
// Prepare the values to put into the query string
$vars = array();
$vars['recipient'] = $_POST['txt_customer_contact_no'];
$vars['sender'] = strtoupper($saloon_info['saloon_name']);
$vars['is_payor'] = $this->conf['sms_is_payor'];
$vars['pay_amount'] = $this->conf['sms_pay_amount'];
$vars['token'] = '5ce7467e9ec045cbbac448ba5a422a02';
$vars['customer_num'] = $this->conf['sms_customer_num'];
$appointment_time = date('H:i', strtotime($app_start_time));
$employee_name = $_POST['hdn_selected_employee_name'];
$sms_msg = t('msg_sms_book_appointment', array(
'%emp_name' => $employee_name,
'%saloon_name' => $_POST['hdn_selected_saloon_name'],
'%time' => $appointment_time,
));
$vars['sms_msg'] = $sms_msg;
// Now, the magic comes into place
$smsURL = $url.'?'.http_build_query($vars);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
if (! curl_exec ($curl)) {
// Something went wrong. Check the status code (at least)
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Do something here.
// If $code >= 500 then the remote server encountered an internal error
// retry later or ask them to fix it
// If 400 <= $code < 500 then there is a problem with the request:
// maybe the resource is not there (404, 410)
// or you are not allowed to access it (403)
// or something else.
echo('Failure sending the SMS. HTTP status code is '.$code."\n");
}
curl_close ($curl);
Check the list of HTTP status codes for more details.
USPS suggests to send request XML to
secure.shippingapis.com/ShippingAPI.dll?API=MerchandiseReturnV4&XML=
I have tried with the example XML given at
https://www.usps.com/business/web-tools-apis/merchandise-return-service-labels-v10-2a.htm
$url="https://secure.shippingapis.com/ShippingAPI.dll";
$api="API=MerchandiseReturnV4&XML=";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
echo result;
but it is returning nothing.....
If the request is approaching the API then it would return the response which can be the proper expected response or the error code with some error detail.
The problem for not getting the proper response might be of the following here-
Wrong XML passed to the query string
Missed some required fields in the XML
Invalid Web Tools Credentials
In order to know the exact Error Code and Details you need to parse the returned XML from the API Server.
You can get the response stream and read the stream to the Stream Reader
string result = null;
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
However I implemented this in .Net MVC but it might help for a head start to find the exact problem.
I forget to put the answers after solving my problem.
Function for connect to usps :-
public function connectToUSPS($url, $api, $xml) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
if (empty($error)) {
return $result;
} else {
return false;
}
}
Function to generate USPS label :-
function create_UspsLabel($shipId, $userId) {
$row = 'contains user data';
$uspsUserName = 'a valid usps user name';
$uspsPassword = 'a valid usps user password';
$retailerName = 'retailer name';
$retailerAddress ='retailer address';
$permitNumber = 'a valid permit number';
$retailerState = 'retailer state;
$retailerCity = 'retailer city';
$retailerZip = 'retailer zip code';
$PDUPoBox = 'pdu box number';
$PDUCity = 'pdu city name';
$PDUState = 'pdu state name';
$PDUZip = 'pdu zip code';
$PDUZip2 = 'pdu zip code2';
$oid = 'order id';
$packageId = "KR" . str_pad(($oid + 1), 5, "0", STR_PAD_LEFT);
$state = 'state';
$xml = '<EMRSV4.0Request USERID="' . $uspsUserName . '" PASSWORD="' . $uspsPassword . '">
<Option>RIGHTWINDOW</Option>
<CustomerName>' . $row->name.' '.$row->lastName . '</CustomerName>
<CustomerAddress1>' . $row->suit . '</CustomerAddress1>';
$xml.=' <CustomerAddress2>' . $row->address1 . '</CustomerAddress2>
<CustomerCity>' . $row->city . '</CustomerCity>
<CustomerState>' . $state . '</CustomerState>
<CustomerZip5>' . $row->zipcode . '</CustomerZip5>
<CustomerZip4 />
<RetailerName>' . $retailerName . '</RetailerName>
<RetailerAddress>' . $retailerAddress . '</RetailerAddress>
<PermitNumber>' . $permitNumber . '</PermitNumber>
<PermitIssuingPOCity>' . $retailerCity . '</PermitIssuingPOCity>
<PermitIssuingPOState>' . $retailerState . '</PermitIssuingPOState>
<PermitIssuingPOZip5>' . $retailerZip . '</PermitIssuingPOZip5>
<PDUPOBox>' . $PDUPoBox . '</PDUPOBox>
<PDUCity>' . $PDUCity . '</PDUCity>
<PDUState>' . $PDUState . '</PDUState>
<PDUZip5>' . $PDUZip . '</PDUZip5>
<PDUZip4>' . $PDUZip2 . '</PDUZip4>
<ServiceType>Priority Mail</ServiceType>
<DeliveryConfirmation>False</DeliveryConfirmation>
<InsuranceValue />
<MailingAckPackageID>' . $packageId . '</MailingAckPackageID>
<WeightInPounds>0</WeightInPounds>
<WeightInOunces>10</WeightInOunces>
<RMA>RMA 123456</RMA>
<RMAPICFlag>False</RMAPICFlag>
<ImageType>TIF</ImageType>
<RMABarcode>False</RMABarcode>
<AllowNonCleansedDestAddr>False</AllowNonCleansedDestAddr>
</EMRSV4.0Request>';
$result = $this->connectToUSPS('https://secure.shippingapis.com/ShippingAPI.dll', 'API=MerchandiseReturnV4&XML=', $xml);
$xml = new SimpleXMLElement($result);
$string = base64_decode($xml->MerchandiseReturnLabel);
if ($string) {
$img_file = fopen(__USPSLABELIMAGE__ . "uspsLabel.tif", "w");
fwrite($img_file, $string);
fclose($img_file);
$imageMagickPath = "/usr/bin/convert";
$dest = __USPSLABELIMAGE__ . "uspsLabel.tif";
$filename = time() . ".png";
$pngDestPath = __USPSLABELIMAGE__ . $filename;
exec("$imageMagickPath -density 72 -channel RGBA -colorspace RGB -background none -fill none -dither None $dest $pngDestPath");
return $filename;
} else {
return "error";
}
}