I'm working a project to request data from api service by sending XML data. The programming language used is PHP
. I have done so much research on the internet and nothing turned up except for using cURL. Is there any other way using PHP to achieve this.
<?php
$xml_data = '<mainservice>
<customer>
<appln_id>myid</appln_id>
<password>mypasss</password>
<cust_id>1234</cust_id>
</customer>
</mainservice>';
This is the data that needs to be send. The id
and password
is for authenticating the API service and cust_id
for retrieving data of that particular customer.
The Result data is also in XML format.
NOTE The service accepts only POST data.
<head>
<meta charset="UTF-8">
<title>test handle response</title>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","URL to Request");
var xmlDoc;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
xmlDoc = xmlhttp.responseXML;
console.log(xmlDoc);
}
};
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
var xml = "<?xml version='1.0'?><query><author>John Steinbeck</author></query>";
xmlhttp.send(xml);
</script>
</head>
<body>
</body>
</html>
You must see
https://davidwalsh.name/web-service-php-mysql-xml-json
Hope you will find your solution.
You can also use this
$xml = file_get_contents('post_xml.xml');
$url = 'http://stg.sa.com/post.asmx/';
$post_data = array(
"xml" => $xml,
);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded
",
'content' => http_build_query($post_data),
),
);
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
Post data using file_get_contents()
funtion
$xml_data = '<mainservice>
<customer>
<appln_id>myid</appln_id>
<password>mypasss</password>
<cust_id>1234</cust_id>
</customer>
</mainservice>';
$postdata = http_build_query(
array(
'xml_data' => $xml_data,
'var2' => 'abc'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.net/submit.php', false, $context);
Get data using file_get_contents() function
<?php
$json_url = "http://api.example.com/test.php?type=menu";
$json = file_get_contents($json_url);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";