I am trying to pass data from my PHP script to my Python script in order to write the data from Python to an XML file.
PHP Script:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['submit']))
{
#--Fetching data from the Form
$fserverId = $_POST['field1'];
$finsname = $_POST['field2'];
$fhost = $_POST['field3'];
$fport = $_POST['field4'];
$fproto = $_POST['field5'];
$fuserName = $_POST['field6'];
$fpassword = $_POST['field7'];
$fkey = $_POST['field8'];
$fcompanyName = $_POST['field9'];
$fofficeAddress = $_POST['field10'];
$fstate = $_POST['field11'];
$fcountry = $_POST['field12'];
$fladmin = $_POST['field13'];
$fphone = $_POST['field14'];
$fmobile = $_POST['field15'];
$femail = $_POST['field16'];
$fdesignation = $_POST['field17'];
$frManager = $_POST['field18'];
$data = " --serverId ".$fserverId." --name ".$finsname." --host ".$fhost." --port ".$fport." --proto ".$fproto." --username ".$fuserName." --password ".$fpassword." --key ".$fkey." --companyName ".$fcompanyName." --officeAddress ".$fofficeAddress." --state ".$fstate." --country ".$fcountry." --ladmin ".$fladmin." --phone ".$fphone." --mobile ".$fmobile." --email ".$femail." --designation ".$fdesignation." --rManager ".$frManager;
#--Parsing the data from PHPscript to CGI
echo "Firewall Creation:: ".$data;
$output = exec('python3 /var/www/cgi-bin/dscr.cgi' .$data);
echo "<pre>hello -------</pre>";
echo "<pre>$output</pre>";
}
?>
Python Script:
import cgi, cgitb
import xml.etree.ElementTree as et
import os
from xml.dom import minidom
import sys
import argparse
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings()
#--ADDING THE XML FILE HERE
base_path = os.path.dirname(os.path.realpath(__file__))
xml_file = os.path.join(base_path, "company.xml")
form = cgi.FieldStorage()
print (xml_file)
#--PARSING THE ARGUMENTS
#--To be used to get arguments from Command Line or Php Script
parser = argparse.ArgumentParser(description ='parser script')
parser.add_argument('--serverId', required=True, help='Server ID to find device info')
parser.add_argument('--name', required=True, help='Name Of the Policy')
parser.add_argument('--host', default='any', help='Host of the IP Address')
parser.add_argument('--port', default='any', help='Port used')
parser.add_argument('--proto', default='any', help='Protocol used')
parser.add_argument('--username', default='any', help='Username')
parser.add_argument('--password', default='any', help='Password')
parser.add_argument('--key', default='any', help='')
parser.add_argument('--companyName', default='any', help='Name of the Company')
parser.add_argument('--officeAddress', default='any', help='Address of the Company')
parser.add_argument('--state', default='any', help='State')
parser.add_argument('--country', default='any', help='Country')
parser.add_argument('--ladmin', default='any', help='Local Admin')
parser.add_argument('--phone', default='any', help='Phone Number')
parser.add_argument('--mobile', default='any', help='Mobile Number')
parser.add_argument('--email', default='any', help='Email Address')
parser.add_argument('--designation', default='any', help='Designation of the concerned')
parser.add_argument('--rManager', default='any', help='Reporting Manager of the concerned Person')
args = parser.parse_args()
#--Associating variables to parsed arguments
name = args.name
host = args.host
port = args.port
proto = args.proto
user = args.username
password = args.password
key = args.key
company = args.companyName
officeAddr = args.officeAddress
state = args.state
country = args.country
ladmin = args.ladmin
phone = args.phone
mobile = args.mobile
email = args.email
designation = args.designation
reportingMgr = args.rManager
#--Retrieving the element tree from XML file
tree = et.parse(xml_file)
root = tree.getroot()
#--Creating Elements and input value
new_name = et.Element("name")
new_name.text = name
new_host = et.Element("host")
new_host.text = host
new_port = et.Element("port")
new_port.text = port
new_proto = et.Element("proto")
new_proto.text = proto
new_user = et.Element("user")
new_user.text = user
new_password = et.Element("password")
new_password.text = password
new_key = et.Element("key")
new_key.text = key
new_companyName = et.Element("companyName")
new_companyName.text = company
new_address = et.Element("address")
new_officeAddr = et.Element("officeAddr")
new_officeAddr.text = officeAddr
new_state = et.Element("state")
new_state.text = state
new_country = et.Element("country")
new_country.text = country
new_contact = et.Element("contact")
new_ladmin = et.Element("ladmin")
new_ladmin.text = ladmin
new_phone = et.Element("phone")
new_phone.text = phone
new_mobile = et.Element("mobile")
new_mobile.text = mobile
new_email = et.Element("email")
new_email.text = email
new_designation = et.Element("designation")
new_designation.text = designation
new_reportingMgr = et.Element("reportingManager")
new_reportingMgr.text = reportingMgr
new_address.append(new_officeAddr)
new_address.append(new_state)
new_address.append(new_country)
new_contact.append(new_ladmin)
new_contact.append(new_phone)
new_contact.append(new_mobile)
new_contact.append(new_email)
new_contact.append(new_designation)
new_contact.append(new_reportingMgr)
new_server = et.Element("server")
new_server.append(new_name)
new_server.append(new_host)
new_server.append(new_port)
new_server.append(new_proto)
new_server.append(new_user)
new_server.append(new_password)
new_server.append(new_key)
new_server.append(new_companyName)
new_server.append(new_address)
new_server.append(new_contact)
root.append(new_server)
str = et.tostring(root)
reparsed = minidom.parseString(str)
tree.write(xml_file)
with open(xml_file, 'w') as output:
output.write(reparsed.toprettyxml(indent="\t"))
On trying to execute, the data does not get written on the XML file but when I pass the arguments through Command Line in the python script, it does get written. So there must be a problem in the call/bridge between the two scripts due to which the data I'm trying to send from PHP to Python is not getting parsed.
Related
I am running a PHP code on docker container hosted in Bluemix. The PHP code calls a python script which is a MQTT based subscribe code. My idea was everytime the subscribed code gets MQTT message it will write the values to a text file. The PHP code will keep on checking every 10 seconds for new values in the file.
The VCAP_ENV variables are getting written correctly. However, the site does not load.
The python script executes successfully when i try it locally. So no errors there too.
My code is as follows:
PHP CODE:
<?php
if( getenv("VCAP_SERVICES") ) {
// get IoT service configuration from Bluemix
$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services, true);
$mysql_config = $services_json["iotf-service"][0]["credentials"];
$org_id = $mysql_config["org"];
$port = $mysql_config["mqtt_u_port"];
$username = $mysql_config["apiKey"];
$password = $mysql_config["apiToken"];
}
// set configuration values
$config = array(
'org_id' => $org_id,
'port' => $port,
'app_id' => 'mymqttfinalservice',
'iotf_api_key' => $username,
'iotf_api_secret' => $password,
'device_id' => '007',
'qos' => 1
);
$file = fopen("VCAP_CONFIG.ini","w");
#fwrite($file,"[config]" . PHP_EOL );
#fwrite($file,"org =" . $org_id . PHP_EOL );
#fwrite($file,"apikey =" . $username . PHP_EOL );
#fwrite($file,"authkey =" . $password . PHP_EOL );
fwrite($file,"[config]" . "\n" );
fwrite($file,"org =" . $org_id . "\n" );
fwrite($file,"apikey =" . $username . "\n" );
fwrite($file,"authkey =" . $password . "\n" );
fclose($file);
$file = file_get_contents('VCAP_CONFIG.ini', true);
echo $file;
$command = 'chmod 777 /app/PythonSubscribeCode.py';
$output = '';
exec ( $command);
$command = 'python3 /app/PythonSubscribeCode.py 2>&1';
$output = exec ($command);
print_r($output);
$x = 1;
while($x == 1)
{
$config = parse_ini_file('Data.ini');
echo json_encode($config);
sleep(5);
}
?>
Python Script:
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import os, json
import time
import configparser
# This is the Subscriber
settings = configparser.ConfigParser()
settings.read('VCAP_CONFIG.ini')
organization = settings['config']['org']
username = settings['config']['apikey']
password = settings['config']['authkey']
#Set the variables for connecting to the iot service
broker = ""
devicename = "007"
topic = "iot-2/type/DesktopApplication/id/007/evt/status/fmt/json"
#topic = 'iot-2/evt/status/fmt/json'
deviceType = "DesktopApplication"
clientID = "a:" + organization + ":appId"
print (clientID)
broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)
if username is not "":
mqttc.username_pw_set(username, password=password)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_message(mosq, obj, msg):
global message
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
def on_message(client, userdata, msg):
writeData = msg.payload.decode('utf-8')
parsed_json = json.loads(writeData)
UDD = parsed_json['UDD']
DDD = parsed_json['DDD']
PH = parsed_json['PH']
Ignition = parsed_json['Ignition']
# add the settings to the structure of the file, and lets write it out...
config = configparser.ConfigParser()
config['Data'] = {'UDD': UDD,
'DDD': DDD,
'PH': PH,
'Ignition':Ignition}
with open('Data.ini', 'w') as configfile:
config.write(configfile)
mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)
#print (test)
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message
mqttc.loop_forever()
Can someone please guide on this?
Do you get any useful error messages from cf ic logs containerid to see what might be failing? As an alternate, you could also try execing into the container (either cf ic exec -ti containerid bash or docker exec...) and run the python script directly to see if that's giving you other errors when running there.
I'm using the Zillow API in order to get some data from user inputs. So far I've been able to correctly use the API to get the desired data from a single input.
The issue I'm running into is when I try and convert my simple block of code into a function that I can reuse multiple times with multiple inputs.Eventually, I want the user to be able to uploaded a CSV file or something and run this function through multiple inputs.
Below is my code that is functioning properly:
HTML
<form action="logic.php" method="post">
<p>Address: <input type="text" name="address"></p>
<p>City/State: <input type="text" name="csz"></p>
<input type="submit">
</form>
PHP
//API Key
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$address."&citystatezip=".$citystatezip;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$addressID;
$estimate_result = file_get_contents($zurl);
$estimate_data = simplexml_load_string($zresult);
$estimate = $zdata->response->zestimate->amount;
echo $estimate;
Now the issue is when I try and wrap both of these up into two separate functions in order to use them for multiple inputs.
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function getAddressID($ad,$cs){
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$ad."&citystatezip=".$cs;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID){
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$aID;
$estimate_result = file_get_contents($estimate_url);
$estimate_data = simplexml_load_string($estimate_result);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID); //Calling function doesn't return anything
If essentially I'm doing this same thing as the first PHP example. Why isn't this working from within a function? Did I overlook something?
Ant help on this would be greatly appreciated.
The problem is that you are using the $api_key variable inside both functions, and that variable is not available there. PHP works a bit different then other languages. You can read up on it here: http://php.net/manual/en/language.variables.scope.php
I suggest you extract a function for calling the api. This way you can declare the api key in that function. It also allows you to easier maintain your code (you could improve your api call by adding some error handling or switching to curl or something). The golden rule of a programmer, Don't Repeat Yourself.
The code could look something like this (untested):
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function callZillow($endpoint, array $params)
{
$params['zws-id'] = 'XXX'; // this would be your api_key
$url = 'http://www.zillow.com/webservice/' . $endpoint . '.htm?' . http_build_query($params);
$result = file_get_contents($url);
return simplexml_load_string($result);
}
function getAddressID($ad, $cs)
{
//Get Address ID From API
$data = callZillow('GetSearchResults', ['address' => $ad, 'citystatezip' => $cs]);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID)
{
//Get Estimate from API (using adressID)
$estimate_data = callZillow('GetZestimate', ['zpid' => $aID]);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID);
I am using kannel sms gateway, to send sms
Sorry, if this question is asked before, but I tried to find solution, but I didn't get any, unfortunately I have to post this question.
I am sending message through php script(smpp client) to smpp server, which connects to bearer box and send message.
There are multiple issues am facing:
1. Am not able to get delivery report
2. Am getting an error in logs of smsbox : ERROR: URL <03b3423a> doesn't start with http://' norhttps://'
I tried different solutions, but none of them are working.
I am in need that if number "A" sends message to number "B", then number "A" should get acknowledgement that message had been delivered to number "B"
Here are my details of configuration files:
kannel.conf
group = core
dlr-storage=internal
admin-port = 13000
smsbox-port = 13001
admin-password = bar
log-file = "/var/log//kannel/kannel.log"
box-deny-ip = "*.*.*.*"
box-allow-ip = "127.0.0.1"
access-log = "/var/log/kannel/access.log"
#---------------------------------------------
# SMSC CONNECTIONS
group = "smsc"
smsc = "http"
smsc-id = "http"
#system-type = "generic"
system-type = "kannel"
port = 13015
log-file = /var/log/kannel/smsc.log
status-success-regex = "success"
status-permfail-regex = "failure"
status-tempfail-regex = "retry later"
generic-status-sent = 200
generic-status-error = 404
#reroute-dlr = true
#transceiver-mode = 0
receive-port=13015
send-url = "http://192.168.1.124:8090"
smsc-username = "cust2"
smsc-password = "cust#123"
connect-allow-ip = "*.*.*.*"
#dlr-url="http://192.168.1.106/dlr.php?type=%d"
#---------------------------------------------
# SMSBOX SETUP
group = smsbox
bearerbox-host = 127.0.0.1
bearerbox-port = 13001
smsbox-id = cust2
#---------------------------------------------
# SEND-SMS USERS
group = sendsms-user
username = cust2
password = cust#123
#user-deny-ip = ""
#user-allow-ip = ""
#---------------------------------------------
# SERVICES
group = sms-service
keyword = default
text = "No service specified"
group = smsbox-route
smsbox-id = cust2
smsc-id = "http"
opensmppbox.conf
group = core
dlr-storage = internal
group = opensmppbox
opensmppbox-id = OPENSMPP
opensmppbox-port = 2775
bearerbox-host = 127.0.0.1
bearerbox-port = 13001
our-system-id = outbind
smpp-logins = /usr/local/kannel/smpplogins.txt
use-systemid-as-smsboxid = true
route-to-smsc = http
log-file = /usr/local/kannel/smppbox.log
transmitter.php
<?php
//print "<pre>";
require_once "smpp.php";
$tx=new SMPP('192.168.1.81',2775);
$tx->debug=true;
$tx->system_type="http";
$tx->addr_npi=1;
$tx->sms_registered_delivery_flag=1;
$tx->sms_sm_default_msg_id=1;
//$tx->dlr_url="http://192.168.1.124/cgi-bim/drl";
//$tx->dlr_url="http://192.168.1.124:8090";
print_r($tx);
//print "open status: ".$tx->state."\n";
$tx->bindTransmitter("cust2","cust#123");
$tx->sms_source_addr_npi=1;
//$tx->sms_source_addr_ton=1;
$tx->sms_dest_addr_ton=1;
$tx->sms_dest_addr_npi=1;
$tx->sendSMS("2121","791400000","Hello world");
//$tx->sendSMS("2121","2121","Hello world!!!");
$tx->close();
unset($tx);
Please let me know, if any further information is needed
Thanks for help in advance
What is the response of the call http://192.168.1.124:8090
send-url = "http://192.168.1.124:8090"
Response must be like success, failure or retry later
status-success-regex = "success"
status-permfail-regex = "failure"
status-tempfail-regex = "retry later"
If the response is correct you will get the correct DLR
I am trying to get the xml rate soap feed from UPS working.
Currently I am getting the error "Wrong version" (__Soapcall Exeption) or "0FailureHard10002The XML document is well formed but the document is not valid1" (Respons from server or php).
I took the example provided in the developers toolkit. I tried everything =>
Change soap version to 1.2
Grab wsdl from remote url instead of on
the disk
I double checked the endpoint and userid, accesskey, pass,
...
Does anyone have a working script ?, or even better can someone correct my mistake :)
Code:
<?php
class UpsRate{
private $access,$userid,$passwd,$wsdl,$operation,$endpointurl;
public function __construct() {
$this->setConfig();
}
public function setConfig($is_test = true){
$this->access = sfConfig::get('app_shipping_ups_access');
$this->userid = sfConfig::get('app_shipping_ups_userid');
$this->passwd = sfConfig::get('app_shipping_ups_password');
$this->wsdl = sfConfig::get('sf_data_dir').'/wsdl/ups/RateWS.wsdl';
$this->operation = "ProcessRate";
$this->endpointurl = $is_test?'https://wwwcie.ups.com/ups.app/xml/Rate':'https://onlinetools.ups.com/ups.app/xml/Rate';
}
private function processRate(){
//create soap request
$option['RequestOption'] = 'Shop';
$request['Request'] = $option;
$pickuptype['Code'] = '01';
$pickuptype['Description'] = 'Daily Pickup';
$request['PickupType'] = $pickuptype;
$customerclassification['Code'] = '01';
$customerclassification['Description'] = 'Classfication';
$request['CustomerClassification'] = $customerclassification;
$shipper['Name'] = 'Trutec';
$shipper['ShipperNumber'] = 'Y5562A';
$address['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$address['City'] = 'Antwerp';
//$address['StateProvinceCode'] = 'MD';
$address['PostalCode'] = '2100';
$address['CountryCode'] = 'BE';
$shipper['Address'] = $address;
$shipment['Shipper'] = $shipper;
$shipto['Name'] = 'Imani Imaginarium';
$addressTo['AddressLine'] = '21 ARGONAUT SUITE B';
$addressTo['City'] = 'ALISO VIEJO';
//$addressTo['StateProvinceCode'] = 'CA';
$addressTo['PostalCode'] = '92656';
$addressTo['CountryCode'] = 'US';
$addressTo['ResidentialAddressIndicator'] = '';
$shipto['Address'] = $addressTo;
$shipment['ShipTo'] = $shipto;
$shipfrom['Name'] = 'Trutec';
$addressFrom['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$addressFrom['City'] = 'Deurne';
//$addressFrom['StateProvinceCode'] = 'MD';
$addressFrom['PostalCode'] = '2100';
$addressFrom['CountryCode'] = 'BE';
$shipfrom['Address'] = $addressFrom;
$shipment['ShipFrom'] = $shipfrom;
$service['Code'] = '03';
$service['Description'] = 'Service Code';
$shipment['Service'] = $service;
$packaging1['Code'] = '02';
$packaging1['Description'] = 'Rate';
$package1['PackagingType'] = $packaging1;
$dunit1['Code'] = 'IN';
$dunit1['Description'] = 'cm';
$dimensions1['Length'] = '5';
$dimensions1['Width'] = '4';
$dimensions1['Height'] = '10';
$dimensions1['UnitOfMeasurement'] = $dunit1;
$package1['Dimensions'] = $dimensions1;
$punit1['Code'] = 'KG';
$punit1['Description'] = 'KG';
$packageweight1['Weight'] = '4';
$packageweight1['UnitOfMeasurement'] = $punit1;
$package1['PackageWeight'] = $packageweight1;
$shipment['Package'] = array( $package1 );
$shipment['ShipmentServiceOptions'] = '';
$shipment['LargePackageIndicator'] = '';
$request['Shipment'] = $shipment;
return $request;
}
public function getRate(){
try {
//nitialize soap client
$client = new SoapClient($this->wsdl , array('soap_version' => 'SOAP_1_1','trace' => 1));
//set endpoint url
$client->__setLocation($this->endpointurl);
//create soap header
$usernameToken['Username'] = $this->userid;
$usernameToken['Password'] = $this->passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $this->access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
//get response
return $client->__soapCall($this->operation ,array($this->processRate()));
}
catch(Exception $ex)
{
echo '<pre>';
return print_r($client->__getLastResponse());
echo '</pre>';
}
}
}
?>
The error notifies that your XML is being correctly formatted but you have included one or more elements that are incompatible. Are you able to dump the XML sent ? This may be easier to determine where the error is being detected.
I wouldn't recommend depending on the examples in the UPS documentation to work, they are for illustrative purposes only and probably have not been updated since the first issue.
I had the same issue, and worked this out:
When I would make test calls, they would work. The endpoint I used for the test calls was
https://wwwcie.ups.com/webservices/Rate
However, when I would change to the live calls, then I would receive the wrong version error. That endpoint is:
https://onlinetools.ups.com/webservices
I reviewed the wsdl document, and found near the end a section that looks like this:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<!-- <soap:address location="https://onlinetools.ups.com/webservices/Rate"/> -->
<!-- CIE (Customer Integration Environment) URL -->
<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>
</wsdl:port>
I noticed that the live version endpoint was commented out, so I changed the section as follows:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<soap:address location="https://onlinetools.ups.com/webservices/Rate"/>
<!-- CIE (Customer Integration Environment) URL -->
<!--<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>-->
</wsdl:port>
I'm not sure this will help anyone else, but this ended up resolving my issues.
I'm trying to fetch a list of results for a search through Amazon API to list products on my website. Everything works except for specifying the page number that I want to retrieve. It always fetches page 1 for some reason.
$SecretAccessKey = "xxx";
$request['AWSAccessKeyId'] = "xxx";
$request['AssociateTag'] = "xxx";
$request['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
$request['ResponseGroup'] = "ItemAttributes,Offers,Images";
$request['ItemPage'] = 1;
$request['Service'] = 'AWSECommerceService';
$request['Version'] = '2011-08-01';
$request['Operation'] = 'ItemSearch';
$request['SearchIndex'] = $search['category_name'];
$request['Keywords'] = $search['text'];
$request['Page'] = 5;
ksort($request); // Sorts in order of key
$Prepend = "GET\nwebservices.amazon.com\n/onca/xml\n";
$String = http_build_query($request);
$PrependString = str_replace('+', '%20', $Prepend . $String);
$Signature = base64_encode(hash_hmac("sha256", $PrependString, $SecretAccessKey, True));
$Signature = urlencode($Signature);
$BaseUrl = "http://webservices.amazon.com/onca/xml?";
$SignedRequest = $BaseUrl . $String . "&Signature=" . $Signature;
// Fetch the generated URL
$xml = simplexml_load_file($SignedRequest);
I've tried with $request['Page'], $request['page'], $request['Pages'] and $request['pages']. None seem to work to pull the correct page. Does anyone know what this parameter is supposed to be named?
Turns out it was ItemPage.
$request['ItemPage'] = 5;