I am attempting to make an xml post request which hit the other server url and post xml data their but the code not working for me here is my code
if ($mail->send()) {
$URL = "server link api based";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml','Content-Length: ' . strlen($xml)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
// echo $output;
if ($output) {
echo "1";
} else {
echo "2";
}
}
} catch (Exception $e) {
echo $e;
}
XML format of data here is the code of xml format
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<data>
<lead>
<key>YaskjdfweuYksdlksid....</key>
<leadgroup>.....</leadgroup>
<site>.....</site>
<introducer>0</introducer>
<source>FDH Quick submission</source>
<medium>FDH Quick submission</medium>
<firstname>' . $firstName . '</firstname>
<lastname>' . $lastName . '</lastname>
<email>' . $userEmail . '</email>
<postcode>' . $postCode . '</postcode>
<contactphone>Yes</contactphone>
<phone1>' . $userPhoneNo . '</phone1>
</lead>
</data>';
1 possible issue is that you're not escaping your strings as you insert them in your XML, which might leave you with a corrupt XML file (eg, & must be escaped as &, < must become <, ' must become ', and so on)
you can xml-encode strings with this function:
function xml_esacpe(string $str, string $charset = 'UTF-8'): string {
if (! strlen ( $str )) {
return "";
}
$ret = htmlspecialchars ( $str, ENT_QUOTES | ENT_SUBSTITUTE | ENT_DISALLOWED | ENT_XML1, $charset, true );
if (! strlen ( $ret )) {
throw new Exception ( "failed to xml-encode input! (most likely wrong charset or corrupted input)" );
}
return $ret;
}
furthermore, you can verify that your XML is valid by doing $isValidXML=#((new DOMDocument())->loadXML($xml)); - it will now be true if the xml is valid, or false if the xml is invalid. - is the xml you're sending actually valid xml?
but in any case, you must elaborate what you mean by the code not working for me - how is it not working?
Related
I use the following to convert a doc file to pdf in PHP:
function CallToApi($fileToConvert, $pathToSaveOutputFile, $apiKey, &$message,$unique_filename)
{
try
{
$fileName = $unique_filename.".pdf";
$postdata = array('OutputFileName' => $fileName, 'ApiKey' => $apiKey, 'file'=>"#".$fileToConvert);
$ch = curl_init("http://do.convertapi.com/word2pdf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
$header=ParseHeader(substr($result,0,$headers["header_size"]));
$body=substr($result, $headers["header_size"]);
curl_close($ch);
if ( 0 < $headers['http_code'] && $headers['http_code'] < 400 )
{
// Check for Result = true
if (in_array('Result',array_keys($header)) ? !$header['Result']=="True" : true)
{
$message = "Something went wrong with request, did not reach ConvertApi service.<br />";
return false;
}
// Check content type
if ($headers['content_type']<>"application/pdf")
{
$message = "Exception Message : returned content is not PDF file.<br />";
return false;
}
$fp = fopen($pathToSaveOutputFile.$fileName, "wbx");
fwrite($fp, $body);
$message = "The conversion was successful! The word file $fileToConvert converted to PDF and saved at $pathToSaveOutputFile$fileName";
return true;
}
else
{
$message = "Exception Message : ".$result .".<br />Status Code :".$headers['http_code'].".<br />";
return false;
}
}
catch (Exception $e)
{
$message = "Exception Message :".$e.Message."</br>";
return false;
}
}
I now want to use the same to convert a ppt to pdf. For which I change
$ch = curl_init("http://do.convertapi.com/word2pdf");
to
$ch = curl_init("http://do.convertapi.com/PowerPoint2Pdf");
but I am not sure why it isnt converting the given input. Is there something that I may be missing?
It's due to PHP 5.6.
You need to add this line to your code as well
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
See:Backward incompatible changes (at the bottom).
I am submitting the contents of an HTML form to a 3rd-party service using cURL, and it shoots me back an XML response. But no matter what I'm doing I can't seem to parse that XML response to customize the display of the results.
Here is the code for processing the form (note a few ID numbers have been censored):
<?php
$FirstName = $_POST['FirstName'] ;
$LastName = $_POST['LastName'] ;
$Zip = $_POST['Zip'] ;
$EmailAddress = $_POST['EmailAddress'] ;
$PrimaryPhoneNumber = $_POST['PrimaryPhoneNumber'] ;
$DateofBirth = $_POST['DateofBirth'] ;
$myvars = '&VID=' . '****' . '&LID=' . '****' . '&AID=' . '****' . '&FirstName=' . $FirstName . '&LastName=' . $LastName .
'&EmailAddress=' . $EmailAddress . '&PrimaryPhoneNumber=' . $PrimaryPhoneNumber . '&Zip=' . $Zip . '&DateofBirth=' . $DateofBirth;
if ($FirstName!='' && $LastName!='' && $Zip!='' && $EmailAddress!='' && $PrimaryPhoneNumber!='' && $DateofBirth!='') {
$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://secure.leadexec.net/leadimport.asmx/LeadReceiver');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $myvars);
curl_exec ($c);
curl_close ($c);
} else {
echo '<p>Please make sure you have filled out the form completely</p>';
}
?>
This is the raw output of the response I get back:
<?xml version="1.0" encoding="utf-8"?>
<PostResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.leadproweb.com/">
<isValidPost>false</isValidPost>
<ResponseType>Duplicate_Lead</ResponseType>
<ResponseDetails>Duplicate Lead, Last Received On: 9/27/2013 2:17:26 PM</ResponseDetails>
<LeadIdentifier>20889333</LeadIdentifier>
<VendorAccountAssigned>0</VendorAccountAssigned>
<PendingQCReview>false</PendingQCReview>
<Price>0</Price>
<RedirectURL />
</PostResponse>
When I try using methods like SimpleXmlElement or simplexml_load_string() to parse the XML, they seem to be ignored and I can't get rid of the raw XML output unless I remove the curl_exec($c) line.
Is there something I am doing wrong?
You need to add
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
to get the value (string) of the response; otherwise, curl_exec just returns a boolean (success/failure). See http://php.net/manual/en/function.curl-exec.php
Then you replace the line
curl_exec( $c );
with
$response = curl_exec( $c );
And finally you parse the response string with a parser of your choice.
Please consider the following code:
$imagePath = "https://s22.postimg.org/3k3o9ly8t/testigo.jpg";
$imagedata = get that image data through curl and store in this variable;
echo strlen($imagedata); // outputs 4699
if(strlen($imagedata) == 4699 ) {
echo "length is 4699";
}
The above if-condition never becomes true even though the strlen value is 4600. It seems very strange; am I missing anything? I've already tried mb_strlen, but to no avail.
Update:
It seems to work for certain images, but not for the following image.
Code:
$strImageURL = "https://s22.postimg.org/3k3o9ly8t/testigo.jpg";
$strImageData = getData($strImageURL);
echo "<br />" . strlen($strImageData);
if(strlen($strImageData) === 4699) {
echo "true";
}
function getData($strSubmitURL)
{
$strData = null;
$ch = curl_init();
//return parameter
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 140);
//site name
curl_setopt($ch, CURLOPT_URL,$strSubmitURL);
// don' verify ssl host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
$strData = curl_exec ($ch);
if (!$strData) {
//die ("cURL error: " . curl_error ($ch) . "\n");
return '';
}
curl_close ($ch);
unset($ch);
return $strData;
}
This works for me:
$url = "http://static.bbci.co.uk/frameworks/barlesque/2.51.4/orb/4/img/bbc-blocks-dark.png";
$imagedata = file_get_contents($url);
//echo strlen($imagedata); // outputs 1020
if(strlen($imagedata) == 1020 ) {
echo "length is 1020";
}
And as further troubleshooting, I would try a var_dump(get_defined_vars()); at the end of your code and inside the if statement to see whats going on.
//Edit/Update:
Using your url, and also putting in a var dump twice:
$url = "http://s22.postimg.org/3k3o9ly8t/testigo.jpg";
$imagedata = file_get_contents($url);
$strlen = strlen($imagedata); // outputs 4669
var_dump($strlen);
if($strlen == 4669 ) {
echo "length is 4669 \n";
var_dump($strlen);
}
returns:
PhpMate running PHP 5.3.15 with (/usr/bin/php)
>>> untitled
int(4669)
length is 4669
int(4669)
strlen() is used to count the bytes that a string equates an one character does not necessarily equal 1 byte in UTF-8
Another issue could be type-casting since PHP has such loose rules about this. Would this work for you?
if((int)strlen($imagedata) == 4600 ) {
echo "length is 4600";
}
or
if(strlen($imagedata) == '4600' ) {
echo "length is 4600";
}
I am using xml with cURL to contact Canada post and
get shipping labels.
This is the code I use.
The platform is ExpressionEngine
<?php
/**
* Sample code for the CreateShipment Canada Post service.
*
* The CreateShipment service is used to create a new shipping item, to
* request the generation of a softcopy image of shipping labels, and to provide
* links to these shipping labels and other information associated with the
* shipping item..
*
* This sample is configured to access the Developer Program sandbox environment.
* Use your development key username and password for the web service credentials.
*
**/
// Your username, password and customer number are imported from the following file
// CPCWS_Shipping_PHP_Samples\REST\shipping\user.ini
$userProperties = parse_ini_file(realpath(dirname($_SERVER['SCRIPT_FILENAME'])) . '/../user.ini');
$username = $userProperties['username'];
$password = $userProperties['password'];
$mailedBy = $userProperties['customerNumber'];
$mobo = $userProperties['customerNumber'];
// REST URL
$service_url = 'https://ct.soa-gw.canadapost.ca/rs/' . $mailedBy . '/' . $mobo . '/shipment';
// Create CreateShipment request xml
$groupId = '4326432';
$requestedShippingPoint = 'H2B1A0';
$mailingDate = '2012-10-24';
$contractId = '0040662521';
$xmlRequest = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<shipment xmlns="http://www.canadapost.ca/ws/shipment">
<group-id>{$groupId}</group-id>
<requested-shipping-point>{$requestedShippingPoint}</requested-shipping-point>
<expected-mailing-date>{$mailingDate}</expected-mailing-date>
<delivery-spec>
<service-code>DOM.EP</service-code>
<sender>
<name>Bulma</name>
<company>Capsule Corp.</company>
<contact-phone>1 (514) 820 5879</contact-phone>
<address-details>
<address-line-1>502 MAIN ST N</address-line-1>
<city>MONTREAL</city>
<prov-state>QC</prov-state>
<country-code>CA</country-code>
<postal-zip-code>H2B1A0</postal-zip-code>
</address-details>
</sender>
<destination>
<name>Ryuko Saito</name>
<company>Kubere</company>
<address-details>
<address-line-1>23 jardin private</address-line-1>
<city>Ottawa</city>
<prov-state>ON</prov-state>
<country-code>CA</country-code>
<postal-zip-code>K1K4T3</postal-zip-code>
</address-details>
</destination>
<options>
<option>
<option-code>DC</option-code>
</option>
</options>
<parcel-characteristics>
<weight>15</weight>
<dimensions>
<length>6</length>
<width>12</width>
<height>9</height>
</dimensions>
<unpackaged>true</unpackaged>
<mailing-tube>false</mailing-tube>
</parcel-characteristics>
<notification>
<email>ryuko.saito#kubere.com</email>
<on-shipment>true</on-shipment>
<on-exception>false</on-exception>
<on-delivery>true</on-delivery>
</notification>
<print-preferences>
<output-format>8.5x11</output-format>
</print-preferences>
<preferences>
<show-packing-instructions>true</show-packing-instructions>
<show-postage-rate>false</show-postage-rate>
<show-insured-value>true</show-insured-value>
</preferences>
<settlement-info>
<contract-id>{$contractId}</contract-id>
<intended-method-of-payment>Account</intended-method-of-payment>
</settlement-info>
</delivery-spec>
</shipment>
XML;
$curl = curl_init($service_url); // Create REST Request
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_CAINFO, realpath(dirname($argv[0])) . '/../../../third-party/cert/cacert.pem'); // Signer Certificate in PEM format
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $xmlRequest);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/vnd.cpc.shipment-v2+xml', 'Accept: application/vnd.cpc.shipment-v2+xml'));
$curl_response = curl_exec($curl); // Execute REST Request
if(curl_errno($curl)){
echo 'Curl error: ' . curl_error($curl) . "\n";
}
echo 'HTTP Response Status: ' . curl_getinfo($curl,CURLINFO_HTTP_CODE) . "\n";
curl_close($curl);
// Example of using SimpleXML to parse xml response
libxml_use_internal_errors(true);
$xml = simplexml_load_string('<root>' . preg_replace('/<\?xml.*\?>/','',$curl_response) . '</root>');
if (!$xml) {
echo 'Failed loading XML' . "\n";
echo $curl_response . "\n";
foreach(libxml_get_errors() as $error) {
echo "\t" . $error->message;
}
} else {
if ($xml->{'shipment-info'} ) {
$shipment = $xml->{'shipment-info'}->children('http://www.canadapost.ca/ws/shipment');
if ( $shipment->{'shipment-id'} ) {
echo 'Shipment Id: ' . $shipment->{'shipment-id'} . "\n";
foreach ( $shipment->{'links'}->{'link'} as $link ) {
echo $link->attributes()->{'rel'} . ': ' . $link->attributes()->{'href'} . "\n";
}
}
}
if ($xml->{'messages'} ) {
$messages = $xml->{'messages'}->children('http://www.canadapost.ca/ws/messages');
foreach ( $messages as $message ) {
echo 'Error Code: ' . $message->code . "\n";
echo 'Error Msg: ' . $message->description . "\n\n";
}
}
}
?>
I received error below
HTTP Response Status: 500 Error Code: Server Error Msg: illegal character 'X' at offset 37 of /rs/0000000000/0000000000/shipment
(I changed customer number to "0000000000")
Can someone explain what is the meaning of above message?
Thank you very much
The provider is probably (like all "enterprise" providers) not using a proper XML parser. Try putting a space before the closing characters of the PI, or failing that remove the PI entirely.
37 characters puts you right at the end of the XML Prolog
<?xml version="1.0" encoding="UTF-8"?>
Either the host does not handle this or you have may have a DOS/UNIX End-of-Line issue.
First, try removing the XML Prolog and see if that helps.
If that doesn't help, then (depending on your editor) save the PHP source as a UNIX file to get the end of line markers right. If that doesn't work, try saving it as a DOS file.
I'm wanted to read a rss feed and store it.for this I m using:-
<?php
$homepage = file_get_contents('http://www.forbes.com/news/index.xml');
$xml = simplexml_load_string($homepage);
echo '<pre>';
print_r($xml);
?>
but first I want to check
1.URL is valid or not ,means if its response time of
$homepage = file_get_contents('http://www.forbes.com/news/index.xml');
is less than 1 minutes and the url address is correct
2.Then check the File(http://www.forbes.com/news/index.xml) have a valid XML data or not.
if valid XML then show response time else show error.
answer Of MY QUESTION:
Thanks everybody for your help and suggestion.I solved this problem. for this I wrote this code
<?php
// function() for valid XML or not
function XmlIsWellFormed($xmlContent, $message) {
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadXML($xmlContent);
$errors = libxml_get_errors();
if (empty($errors))
{
return true;
}
$error = $errors[ 0 ];
if ($error->level < 3)
{
return true;
}
$lines = explode("r", $xmlContent);
$line = $lines[($error->line)-1];
$message = $error->message . ' at line ' . $error->line . ': ' . htmlentities($line);
return false;
}
//function() for checking URL is valid or not
function Visit($url){
$agent = $ch=curl_init();
curl_setopt ($ch, CURLOPT_URL,$url );
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch,CURLOPT_VERBOSE,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_SSLVERSION,3);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
$page=curl_exec($ch);
//echo curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300) return true;
else return false;
}
$url='http://www.forbes.com/news/index.xml';
if (Visit($url)){
$xmlContent = file_get_contents($url);
$errorMessage = '';
if (XmlIsWellFormed($xmlContent, $errorMessage)) {
echo 'xml is valid';
$xml = simplexml_load_string($xmlContent);
echo '<pre>';
print_r($xml);
}
}
?>
If the url is not valid file_get_contents would fail.
To check if the xml is valid
simplexml_load_string(file_get_contents('http://www.forbes.com/news/index.xml'))
That would return true if its and would fail entirely if it isn't.
if(simplexml_load_string(file_get_contents('http://www.forbes.com/news/index.xml'))){
echo "yeah";
}else { echo "nah";}
This page has a snippet with a validator for a URL using regular expressions. The function and usage:
function isValidURL($url)
{
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
if(!isValidURL($fldbanner_url))
{
$errMsg .= "* Please enter valid URL including http://<br>";
}
if (!filter_var('anyurl',FILTER_VALIDATE_URL))
echo "Wrong url";
end;
http://php.net/manual/en/filter.filters.validate.php