Tuesday, October 4, 2011

php-How to post XML using socket ?


 i had discussed posting XML over HTTP using CURL in last post. Remember that was first method.
As I had promised on earlier post I would like to share second method with you. That is socket!!
Use this code and send your XML file.
View Code PHP
<?php
function postXMLToURL ($server, $path, $xmlDocument) {
$contentLength = strlen($xmlDocument);
$fp = fsockopen($server, 80, $errno, $errstr, 30);
fputs($fp, "POST $path HTTP/1.0rn");
fputs($fp, "Host: $serverrn");
fputs($fp, "Content-Type: text/xmlrn");
fputs($fp, "Content-Length: $contentLengthrn");
fputs($fp, "Connection: closern");
fputs($fp, "rn"); // all headers sent
fputs($fp, $xmlDocument);
$result = '';
while (!feof($fp)) {
$result .= fgets($fp, 128);
}
return $result;
}
 
function getBody ($httpResponse) {
$lines = preg_split('/(rn|r|n)/', $httpResponse);
$responseBody = '';
$lineCount = count($lines);
for ($i = 0; $i < $lineCount; $i++) {
if ($lines[$i] == '') {
break;
}
}
for ($j = $i + 1; $j < $lineCount; $j++) {
$responseBody .= $lines[$j] . "n";
}
return $responseBody;
}
 
$xmlpacket ='<AATHtlDispReq1>
<Agency>
<Iata>1234567890</Iata>
<Agent>lgsoftwares</Agent>
<Password>myapassword</Password>
<Brand>phpmind.com</Brand>
</Agency>
<Passengers>
<Adult AGE="" ID="1"></Adult>
<Adult AGE="" ID="2"></Adult>
</Passengers>
<DestCode>OGG</DestCode>
<CheckInDate>101009</CheckInDate>
</AATHtlDispReq1>';
 
 
$result = postXMLtoURL("www.yourdomain.com", "/path/",$xmlpacket);
 
$responseBody = getBody($result);
 
echo $responseBody;
?>

No comments: