I've created an LTI enabled tool and am having some trouble with sending data back to an LMS such as Desire2Learn. Based on my understanding alone, you generate an XML payload containing the grade item itself and send this via POST back to the LMS using cURL. The problem I'm running into is that my $result variable is returning false and I can't figure it out right now. Here is my code:
session_start();
require_once 'blti/blti.php';
require_once 'blti/blti_util.php';
define('OAUTH_CONSUMER_KEY', 'key');
define('OAUTH_CONSUMER_SECRET', 'secret');
$blti = new BLTI(OAUTH_CONSUMER_SECRET, true, false);
if ($blti->valid) {
$_SESSION['lis_outcome_service_url'] = $_REQUEST['lis_outcome_service_url'];
$_SESSION['lis_result_sourcedid'] = $_REQUEST['lis_result_sourcedid'];
$_SESSION['lis_person_name_given'] = $_REQUEST['lis_person_name_given'];
$_SESSION['oauth_consumer_key'] = $_REQUEST['oauth_consumer_key'];
$_SESSION['oauth_consumer_secret'] = OAUTH_CONSUMER_SECRET;
sendGradeBackToLMS();
}else {
exit($blti->message);
}
function sendGradeBackToLMS() {
$ch = curl_init();
if (!$ch) { exit('curl is not supported!'); }
$url = 'http://localhost/endpoint.php';
$xmldata = getPOXRequest();
$xml = str_replace(
array('MESSAGE_IDENTIFIER', 'SOURCEDID', 'GRADE'),
array(uniqid(), $_SESSION['lis_result_sourcedid'], 0.75),
$xmldata);
$request_headers = array();
$request_headers[] = 'User-Agent: '. $_SERVER['HTTP_USER_AGENT'];
$request_headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $request_headers,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $xml
));
$results = curl_exec($ch);
curl_close($ch);
echo $results;
}
function getPOXRequest() {
return <<<XML
<?xml version = "1.0" encoding = "UTF-8"?>
<imsx_POXEnvelopeRequest xmlns = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
<imsx_POXHeader>
<imsx_POXRequestHeaderInfo>
<imsx_version>V1.0</imsx_version>
<imsx_messageIdentifier>MESSAGE_IDENTIFIER</imsx_messageIdentifier>
</imsx_POXRequestHeaderInfo>
</imsx_POXHeader>
<imsx_POXBody>
<replaceResultRequest>
<resultRecord>
<sourcedGUID>
<sourcedId>SOURCEDID</sourcedId>
</sourcedGUID>
<result>
<resultScore>
<language>en</language>
<textString>GRADE</textString>
</resultScore>
</result>
</resultRecord>
</replaceResultRequest>
</imsx_POXBody>
</imsx_POXEnvelopeRequest>
XML;
}
Just to summarize it up, $blti is an instance that checks if it is a valid Basic LTI launch or not. If that is true, I initialize the SESSION by storing LTI request variables into SESSION variables. Next in the sendGradeBackToLMS() function I send a block of XML data containing the grade item to the path given in $url.
Any kind of input would be helpful!
Thanks!
Try this code,
require_once("ims-blti/OAuthBody.php");
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
} else {
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
}
$method="POST";
$oauth_consumer_secret = $_REQUEST['secret'];
$sourcedid = $_REQUEST['lis_result_sourcedid'];
if (get_magic_quotes_gpc()) $sourcedid = stripslashes($sourcedid);
$oauth_consumer_key = $_REQUEST['key'];
$endpoint = $_REQUEST['lis_outcome_service_url'];
$content_type = "application/xml";
$body = '<?xml version = "1.0" encoding = "UTF-8"?>
<imsx_POXEnvelopeRequest xmlns = "http://www.imsglobal.org/lis/oms1p0/pox">
<imsx_POXHeader>
<imsx_POXRequestHeaderInfo>
<imsx_version>V1.0</imsx_version>
<imsx_messageIdentifier>MESSAGE</imsx_messageIdentifier>
</imsx_POXRequestHeaderInfo>
</imsx_POXHeader>
<imsx_POXBody>
<OPERATION>
<resultRecord>
<sourcedGUID>
<sourcedId>SOURCEDID</sourcedId>
</sourcedGUID>
<result>
<resultScore>
<language>en-us</language>
<textString>GRADE</textString>
</resultScore>
</result>
</resultRecord>
</OPERATION>
</imsx_POXBody>
</imsx_POXEnvelopeRequest>';
if (isset($_REQUEST['grade'])) {
$operation = 'replaceResultRequest';
$postBody = str_replace(
array('SOURCEDID', 'GRADE', 'OPERATION','MESSAGE'),
array($sourcedid, $_REQUEST['grade'], $operation, uniqid()),
$body);
} else {
exit();
}
$response = sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $postBody);
Check this out,
git clone https://github.com/ebinezar/ims-lti.git
Related
I am currently trying to figure out how to upload my own invoice pdf files to Amazon MWS with php/curl:
1.) Upload pdf to Amazon MWS using Action: SubmitFeed and FeedType: UPLOAD_VAT_INVOICE
This is giving a positive response with a FeedSubmissionId
2.) Get Feed Submission Result with that FeedSubmissionId is reporting an Error 79523 "Please provide only one valid marketplace while uploading an invoice."
So I assume that my upload is not working properly, but I can not find the mistake.
The Error Code is described on Page 21 in this PDF File from Amazon: VAT Calculation Service (VCS) Developer Guide
I have spent 2 days so far, trying to solve this, and I was not able to find anything about it on google. Hope someone here can help me. Thanks!
Here is the code:
<?php
$param = array();
$param['AWSAccessKeyId'] = 'XXXXX';
$param['Action'] = 'SubmitFeed';
$param['Merchant'] = 'XXXXX';
$param['FeedType'] = '_UPLOAD_VAT_INVOICE_';//'_POST_ORDER_FULFILLMENT_DATA_';
$param['FeedOptions'] = 'metadata:OrderId='.$amz_order_id.';metadata:TotalAmount='.$TotalAmount.';metadata:TotalVATAmount='.$TotalVATAmount.';metadata:InvoiceNumber='.$InvoiceNumber.';metadata:documenttype=Invoice';
$param['SignatureMethod'] = 'HmacSHA256';
$param['SignatureVersion'] = '2';
$param['Timestamp'] = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
$param['Version'] = '2009-01-01';
$param['MarketplaceIdList.Id.1'] = 'A1PA6795UKMFR9';
$param['PurgeAndReplace'] = 'false';
$secret = 'XXXXX';
$url = array();
foreach ($param as $key => $val) {
$key = str_replace("%7E", "~", rawurlencode($key));
$val = str_replace("%7E", "~", rawurlencode($val));
$url[] = "{$key}={$val}";
}
sort($url);
$file = fopen($link_to_pdf_file,"r");
$pdf_feed=fread($file,filesize($FileName));
fclose($file);
$amazon_feed='<?xml version="1.0" encoding="utf-8"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.01</DocumentVersion>
<MerchantIdentifier>'.$param['Merchant'].'</MerchantIdentifier>
</Header>
<MessageType>OrderFulfillment</MessageType>
<Message>
<MessageID>'.getserial().'</MessageID>
<OrderFulfillment>
<AmazonOrderID>'.$amz_order_id.'</AmazonOrderID>
<FulfillmentDate>'.$param['Timestamp'].'</FulfillmentDate>
<FulfillmentData>
<CarrierName>Deutsche Post</CarrierName>
<ShippingMethod>Brief</ShippingMethod>
<ShipperTrackingNumber></ShipperTrackingNumber>
</FulfillmentData>
</OrderFulfillment>
</Message>
</AmazonEnvelope>';
$arr = implode('&', $url);
$sign = 'POST' . "\n";
$sign .= 'mws.amazonservices.de' . "\n";
$sign .= '/Feeds/'.$param['Version'].'' . "\n";
$sign .= $arr;
$signature = hash_hmac("sha256", $sign, $secret, true);
$httpHeader = array();
$httpHeader[] = 'Transfer-Encoding: chunked';
$httpHeader[] = 'Content-Type: application/octet-stream';//application/pdf
$httpHeader[] = 'Content-MD5: ' . base64_encode(md5($pdf_feed, true));
$httpHeader[] = 'Expect:';
$httpHeader[] = 'Accept:';
$signature = urlencode(base64_encode($signature));
$link = "https://mws.amazonservices.de/Feeds/".$param['Version']."?";
$link .= $arr . "&Signature=" . $signature;
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $amazon_feed);
$response['reply'] = curl_exec($ch);
$response['info'] = curl_getinfo($ch);
curl_close($ch);
?>
There is no XML to post with this feed. FeedContent (CURLOPT_POSTFIELDS) is the content of the PDF ($pdf_feed)
I'm trying to create registration using REST API NotificationHub AZURE from PHP API Microsoft
¿Anyone know how it's done?
Regards and thanks!
Generally speaking, there are 3 main steps required to access Notification Hubs REST endpoints:
Parse the connection string
Generate the authorization token
Perform the HTTP call
You can refer to https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-php-backend-how-to/ for more detail.
Meanwhile, you can directly use these PHP sample provided by Azure Team in your application, which can implement your requirements easily.
# build uri
$uri = $this->endpoint . $this->hubPath . "/registrations" . NotificationHub::API_NEW_VERSION;
$ch = curl_init();
$token = $this->generateSasToken($uri);
$headers = [
'Authorization: '. $token,
'Content-Type: application/xml',
'x-ms-version: 2015-01'
];
$request_body = self::requestBodyRegistration($device_type, $tagsOrTagExpression, $device_code );
if( is_null( $request_body ) )
{
return null;
}
curl_setopt_array($ch, array(
CURLOPT_URL => $uri,
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $request_body
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
curl_close($ch);
private function requestBodyRegistration($device_type, $tagsOrTagExpression, $device_code )
{
switch ($device_type) {
case 'apple':
return '<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
<AppleRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<Tags>'. $tagsOrTagExpression .'</Tags>
<DeviceToken>'. $device_code .'</DeviceToken>
</AppleRegistrationDescription>
</content>
</entry>';
case 'gcm':
return '<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
<GcmRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<Tags>'. $tagsOrTagExpression .'</Tags>
<GcmRegistrationId>'. $device_code .'</GcmRegistrationId>
</GcmRegistrationDescription>
</content>
</entry>';
default:
return null;
}
}
I am trying to verify receipt from Windows Store using PHP.
I am using following code:
<?php
include('Crypt/RSA.php');
include('File/X509.php');
$xml_str ='<Receipt Version="1.0" ReceiptDate="2012-08-30T23:08:52Z" CertificateId="b809e47cd0110a4db043b3f73e83acd917fe1336" ReceiptDeviceId="4e362949-acc3-fe3a-e71b-89893eb4f528">
<ProductReceipt Id="6bbf4366-6fb2-8be8-7947-92fd5f683530" ProductId="Product1" PurchaseDate="2012-08-30T23:08:52Z" ExpirationDate="2012-09-02T23:08:49Z" ProductType="Durable" AppId="55428GreenlakeApps.CurrentAppSimulatorEventTest_z7q3q7z11crfr" />
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<DigestValue>Uvi8jkTYd3HtpMmAMpOm94fLeqmcQ2KCrV1XmSuY1xI=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>TT5fDET1X9nBk9/yKEJAjVASKjall3gw8u9N5Uizx4/Le9RtJtv+E9XSMjrOXK/TDicidIPLBjTbcZylYZdGPkMvAIc3/1mdLMZYJc+EXG9IsE9L74LmJ0OqGH5WjGK/UexAXxVBWDtBbDI2JLOaBevYsyy+4hLOcTXDSUA4tXwPa2Bi+BRoUTdYE2mFW7ytOJNEs3jTiHrCK6JRvTyU9lGkNDMNx9loIr+mRks+BSf70KxPtE9XCpCvXyWa/Q1JaIyZI7llCH45Dn4SKFn6L/JBw8G8xSTrZ3sBYBKOnUDbSCfc8ucQX97EyivSPURvTyImmjpsXDm2LBaEgAMADg==</SignatureValue>
</Signature>
</Receipt>';
if( !$xml = simplexml_load_string( $xml_str ) )
{
echo 'Unable to load XML string<br />';
}
else
{
print 'XML String loaded successfully<br />';
}
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, "https://lic.apps.microsoft.com/licensing/certificateserver/?cid=".$xml["CertificateId"]);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$responseFromServer = curl_exec($ch);
//echo $responseFromServer;
echo '<br/>';
$x509 = new File_X509();
$cert=$x509->loadX509($responseFromServer);
print_r($cert);
echo $x509->getPublicKey();
echo '<br/>';
//close connection
curl_close($ch);
$signatureInfo2='<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<DigestValue>Uvi8jkTYd3HtpMmAMpOm94fLeqmcQ2KCrV1XmSuY1xI=</DigestValue>
</Reference>
</SignedInfo>';
$data = $xml->Signature->SignatureValue;
echo $data;
echo '<br/>';
$dom = new DOMDocument();
$dom->loadXML($signatureInfo2);
$canonicalized = $dom->C14N(TRUE, FALSE);
echo $canonicalized;
echo '<br/>';
$rsa = new Crypt_RSA();
$key = $x509->getPublicKey();
$key1 = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnK+P74KmRbczKst4ztFx 4wVDceo+2U1xJzaS5dlUns1UAPSitkZb66FyoWDFFHSacPrcZtZqov1uw/UDmE6t XvNxi4VgvSEYfzkpkmLdHpIFSwfonMkR93baWHCebLKVNobj3+CPzXNOjrl5TLA/ TFOFIPSAQ9h0gwRKroRkaMVeuGLhB+OuOaAdeC5RGstPiWZZCmf5lYcf7Hc0gX63 WtV/wpHO0joJ00jN3fw5zuQysFdlmJ/u4v6wanuP6KeiKkDKz6R8npvUp8votMYl DAPtSMJF9IbNILxzOsw8MEzA4k2qWwsvS55jMeuaDKueoYbEMnSxJqrqvJVWFAxMywIDAQAB';
if($rsa->loadKey($key1))
{ // public key
$rsa->setPublicKey();
$rsa->setHash('sha256');
echo $rsa->verify($canonicalized, $data) ? 'verified' : 'unverified';
}
?>
I am following this link. But I am always getting "bad" as output.
Can somebody tell me what I am doing wrong here?
Thanks
I managed to verify WP8 IAP receipt using xmlseclibs library. Windows Store is not much different.
Also, you need php curl enabled.
do {
$doc = new DOMDocument();
$xml = $_POST['receipt_data']; // your receipt xml here!
// strip unwanted chars - IMPORTANT!!!
$xml = str_replace(array("\n","\t", "\r"), "", $xml);
//some (probably mostly WP8) receipts have unnecessary spaces instead of tabs
$xml = preg_replace('/\s+/', " ", $xml);
$xml = str_replace("> <", "><", $xml);
$doc->loadXML($xml);
$receipt = $doc->getElementsByTagName('Receipt')->item(0);
$certificateId = $receipt->getAttribute('CertificateId');
$ch = curl_init("https://lic.apps.microsoft.com/licensing/certificateserver/?cid=$certificateId");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$publicKey = curl_exec($ch);
$errno = curl_errno($ch);
$errmsg = curl_error($ch);
curl_close($ch);
if ($errno != 0) {
$verifyFailed = true;
break;
}
// Verify xml signature
require('./xmlseclibs.php');
$objXMLSecDSig = new XMLSecurityDSig();
$objDSig = $objXMLSecDSig->locateSignature($doc);
if (!$objDSig) {
$verifyFailed = true;
break;
}
try {
$objXMLSecDSig->canonicalizeSignedInfo();
$retVal = $objXMLSecDSig->validateReference();
if (!$retVal) {
throw new Exception("Error Processing Request", 1);
}
$objKey = $objXMLSecDSig->locateKey();
if (!$objKey) {
throw new Exception("Error Processing Request", 1);
}
$key = NULL;
$objKeyInfo = XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig);
if (! $objKeyInfo->key && empty($key)) {
$objKey->loadKey($publicKey);
}
if (!$objXMLSecDSig->verify($objKey)) {
throw new Exception("Error Processing Request", 1);
}
} catch (Exception $e) {
$verifyFailed = true;
break;
}
$productReceipt = $doc->getElementsByTagName('ProductReceipt')->item(0);
$prodictId = $productReceipt->getAttribute('ProductId');
$purchaseDate = $productReceipt->getAttribute('PurchaseDate');
} while(0);
if ($verifyFailed) {
// invalid receipt
} else {
// valid receipt
}
If you are dealing with WP8 in-app purchase, the CertificateId in the xml may look like this A656B9B1B3AA509EEA30222E6D5E7DBDA9822DCD. But the following link gives 404 error:
https://lic.apps.microsoft.com/licensing/certificateserver/?cid=A656B9B1B3AA509EEA30222E6D5E7DBDA9822DCD
So you cannot get the certificate with curl. Instead, replace the curl part with this:
$publicKey = <<<EOT
-----BEGIN CERTIFICATE-----
MIIDFDCCAgCgAwIBAgIQrih3cQuSeL1CgpLFusfJsTAJBgUrDgMCHQUAMB8xHTAb
BgNVBAMTFElhcFJlY2VpcHRQcm9kdWN0aW9uMB4XDTEyMDIxNzAxMTYyNFoXDTM5
MTIzMTIzNTk1OVowHzEdMBsGA1UEAxMUSWFwUmVjZWlwdFByb2R1Y3Rpb24wggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDb0CeltVqOOIJiwNGgAr7Z0K4r
AYsHCa1oSFPJXtokz134bi2neJ8bHIKAnT0kwa3xViUxwp3+OZd2t2PshDv0ucZ5
dus6WCnuAw/MHVAodgLQMqYiKeM7VTIi3S1s3iV/66Y8KP7jH3CmE2XCXOQae+bQ
UuyGsTit0ScU7+MofODoNhvONs54n/K1WVnct2wWBpn8GGAS+l2mzOF0jXbMSjtz
7wuK77GeydG+x9paLuHIyCso7tjOqv/lvol5IIX0VnC5G2vC6dWR6MkNL5FzLXns
SuQgoYEUZXPlXJhsmv6oyyenaP0PpYJZcCLLVi1L2hcVo8B2DIEg3I3t8ch/AgMB
AAGjVDBSMFAGA1UdAQRJMEeAEHGLK3BRpCWDa2vU50kI73ehITAfMR0wGwYDVQQD
ExRJYXBSZWNlaXB0UHJvZHVjdGlvboIQrih3cQuSeL1CgpLFusfJsTAJBgUrDgMC
HQUAA4IBAQC4jmOu0H3j7AwVBvpQzPMLBd0GTimBXmJw+nruE+0Hh/0ywGTFNE+K
cQ21L4v+IuP8iMh3lpOcPb23ucuaoNSdWi375/KxrW831dbh+goqCZP7mWbxpnSn
FnuV+R1VPsQjdS+0tg5gjDKNMSx/2fH8krLAkidJ7rvUNmtEWMeVNk0/ZM/ECino
bMSSwbqUuc9Qql9T1epe+xv34a6eek+m4W0VXnLSuKhQS5jdILsyeJWHROZF5mrh
3DQuS0Ll5FzKmJxHf0hyXAo03SSA+x3JphAU4oYbkE9nRTU1tR6iq1D9ZxfQmvzm
IbMfyJ/y89PLs/ewHopSK7vQmGFjfjIl
-----END CERTIFICATE-----
EOT;
(The certificate is from MSDN sample code. I converted it to PEM format.)
It now works XD!
Your $canonicalized should only content the receipt with "Signature" element (and all it's child nodes) removed. after that, you can do a base64_encode(hash('sha256', $canonicalized,TRUE)) to see if match the DigestValue before go for verify stage.
Besides the above issue,the receipt & cert you are using is outdated, even the "offical sample" from Microsoft: http://code.msdn.microsoft.com/wpapps/In-app-purchase-receipt-c3e0bce4
also fails to verify the signature using their c# example code.
I spend days to find a working receipt and cert online but end up no luck =(
I'm trying to send some information to our CRM from a form on our site and am getting stuck on inserting the variables into the XML. Here is a simplified version of my code. Notice where I'm trying to insert the $email variable within the XML variable...which is not working.
<?php
$email = $_GET["email"];
$xml = '<xmlrequest>
<details>
<emailaddress>$email</emailaddress>
<mailinglist>8</mailinglist>
<format>html</format>
<confirmed>no</confirmed>
</details>
</xmlrequest>
';
$ch = curl_init('http://mysite.com/xml.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
$result = #curl_exec($ch);
if ($result === false) {
echo "Error performing request";
} else {
$xml_doc = simplexml_load_string($result);
header( "Location: http://mysite.com/confirmation?email=$email" ) ;
//echo 'Status is ', $xml_doc -> status, '<br/>';
if ($xml_doc -> status == 'SUCCESS') {
echo 'Data is ', $xml_doc -> data, '<br/>';
} else {
echo 'Error is ', $xml_doc -> errormessage, '<br/>';
}
}
?>
If I just type in an email address value for the API works fine. However, I'm clueless on how to pull this in dynamically from a PHP variable. Any help is greatly appreciated!
The string definition is bad
use this
$xml = "<xmlrequest>
<details>
<emailaddress>{$email}</emailaddress>
<mailinglist>8</mailinglist>
<format>html</format>
<confirmed>no</confirmed>
</details>
</xmlrequest>";
or this
$xml = '<xmlrequest>
<details>
<emailaddress>' . $email . '</emailaddress>
<mailinglist>8</mailinglist>
<format>html</format>
<confirmed>no</confirmed>
</details>
</xmlrequest>';
Because this variable probably can be various string I think it's better if you use <![CDATA[]]> section around the email.
I have this code that is pulling info from my database and then checking it against an API. I'm trying to customize the return information into a table. I'll include a picture to show what I would like. I've searched everywhere and I don't know how to code this. Don't worry about the CSS it's just getting the information to fill a table.
<?php
$key = "********************";
$address = urlencode($CustomFields->field('jr_address',$listing,false,false));
$city = $listing['Category']['title'];
$zip = $CustomFields->field('jr_zipcode',$listing,false,false);
$url = "http://api.greatschools.org/schools/nearby?key={$key}&address={$address}&city={$city}&state=MI&zip={$zip}&schoolType=public-charter&levelCode=elementary-schools&minimumSchools=50&radius=10&limit=5";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
print_r($response);
?><style type='text/css'>gsId{display:none;}name{color:#9BB055; font-size:18px;}type{display:none;}gradeRange{}enrollment{}gsRating{}city{display:none;}state{display:none;}district{}districtNCESId{display:none;}address{display:none;}phone{display:none; }fax{display:none;}ncesId{display:none;}lat{display:none;}lon{display:none;}</style>
The Return Code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<schools>
<school>
<gsId>6350</gsId>
<name>Chinese Education Center</name>
<type>public</type>
<gradeRange>K-5</gradeRange>
<enrollment>63</enrollment>
<gsRating>3</gsRating>
<city>San Francisco</city>
<state>CA</state>
<district>San Francisco Unified School District</district>
<districtNCESId>0634410</districtNCESId>
<address>657 Merchant St., San Francisco, CA 94111</address>
<phone>(415) 291-7918</phone>
<fax>(415) 291-7965</fax>
<ncesId>063441005596</ncesId>
<lat>37.795</lat>
<lon>-122.4042</lon>
<overviewLink>http://www.greatschools.org/california/san-francisco/6350-Chinese-Education-Center/?s_cid=gsapi</overviewLink>
<ratingsLink>http://www.greatschools.org/school/rating.page?state=CA&id=6350&s_cid=gsapi</ratingsLink>
<reviewsLink>http://www.greatschools.org/school/parentReviews.page?state=CA&id=6350&s_cid=gsapi</reviewsLink>
</school>
<school>
<gsId>6389</gsId>
<name>Gordon J. Lau Elementary School</name>
<type>public</type>
<gradeRange>K-5</gradeRange>
<enrollment>667</enrollment>
<gsRating>7</gsRating>
<city>San Francisco</city>
<state>CA</state>
<district>San Francisco Unified School District</district>
<districtNCESId>0634410</districtNCESId>
<address>950 Clay St., San Francisco, CA 94108</address>
<phone>(415) 291-7921</phone>
<fax>(415) 291-7952</fax>
<website>http://www.gjles.org/</website>
<ncesId>063441005599</ncesId>
<lat>37.794</lat>
<lon>-122.4086</lon>
<overviewLink>http://www.greatschools.org/california/san-francisco/6389-Gordon-J.-Lau-Elementary-School/?s_cid=gsapi</overviewLink>
<ratingsLink>http://www.greatschools.org/school/rating.page?state=CA&id=6389&s_cid=gsapi</ratingsLink>
<reviewsLink>http://www.greatschools.org/school/parentReviews.page?state=CA&id=6389&s_cid=gsapi</reviewsLink>
</school>
</schools>
I don't know how to write the script to make it look like this:
Link to image:
link text
So the new file looks like this?
<?php
$key = "xxxxxxxxxxxxxxxxxxxxxxxx";
$address = urlencode($CustomFields->field('jr_address',$listing,false,false));
$city = $listing['Category']['title'];
$zip = $CustomFields->field('jr_zipcode',$listing,false,false);
$url = "http://api.greatschools.org/schools/nearby?key={$key}&address={$address}&city={$city}&state=MI&zip={$zip}&schoolType=public-charter&levelCode=elementary-schools&minimumSchools=50&radius=10&limit=5";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
echo (xml2html($response, "/xslt/schools.xsl");
?>
I get an error on the echo line.
Where does this go?
<?php
function xml2html($xmldata, $xslPath)
{
/* $xmldata -> your XML */
/* $xsl -> XSLT file */
$arguments = array('/_xml' => $xmldata);
$xsltproc = xslt_create();
xslt_set_encoding($xsltproc, 'ISO-8859-1');
$html =
xslt_process($xsltproc, 'arg:/_xml', $xslPath, NULL, $arguments);
if (empty($html)) {
die('XSLT processing error: '. xslt_error($xsltproc));
}
xslt_free($xsltproc);
return $html;
}
?>
Browsers are unable to visualize custom XML (i.e. your schools xml).
So you should manually transform it to HTML. I know 2 solutions:
Parse XML with xml parser functions
Transform XML by XSLT sheet (as for me, better approach).
For offerred XML I've written next XSLT: link text (sorry for external link, I have unexplainable troubles with pasting XSLT code here)
Transformation could be applied by the function xslt_process. (You should store xsl file somewhere in your server's folder (for example "xslt/schools.xsl") and convert xml response):
<?php
function xml2html($xmldata, $xslPath)
{
/* $xmldata -> your XML */
/* $xsl -> XSLT file */
$arguments = array('/_xml' => $xmldata);
$xsltproc = xslt_create();
xslt_set_encoding($xsltproc, 'ISO-8859-1');
$html =
xslt_process($xsltproc, 'arg:/_xml', $xslPath, NULL, $arguments);
if (empty($html)) {
die('XSLT processing error: '. xslt_error($xsltproc));
}
xslt_free($xsltproc);
return $html;
}
// making request...
$response = curl_exec($curl);
curl_close($curl);
echo(xml2html($response, "/xslt/schools.xsl"));
?>