The client API want me to reply back with a xml - php

I am working on an API in php. The client API sent the results to my url as an xml file. I use file_get_contents to read the xml file they want me to reply back <xml>Accepted</xml>. How to do this?
Example:
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
//Read the xmlinput and write to the file
$xml = file_get_contents('php://input');
// ..Do something..
return('<?xml version="1.0" encoding="utf-8"?><xml>Accepted</xml>');
}
I am not sure how to send back xml to same session without initiating new curl.
Can we use CGI? If so, how?

Are you using SoapClient? if so is it compliant with the version 1.2?
<?php
// ...
$client = new SoapClient('some.wsdl', ['soap_version' => SOAP_1_2]);
You can output this (RFC7303 superseded RFC3023).
<?php
// ...
header('Content-Type: text/html; charset=utf-8');
echo "<?xml version='1.0' encoding='UTF-8'?>";

Related

How can I read a XML file in PHP and generate a XML response?

I´m a total newbie on PHP.
I´ve a XML file that I´ve to read, and then write as response to a PHP call.
<?php
$my_file = 'myfile.txt';
echo htmlspecialchars(file_get_contents($my_file), ENT_QUOTES);
?>
I tried that, but I guess the response is the xml content but encoded as html.
How can I return a proper xml response?
UPDATED: SOLVED
<?php
$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$sentinel = fread($handle,filesize($my_file));
header("Content-type: text/xml; charset=utf-8");
$content = file_get_contents($stations);
echo $content;
?>
Thanks.
The question should not be how to generate XML response, but how to make the browser understand that the content of the response is XML.
To do so you should use the header function:
header("Content-type: text/xml; charset=utf-8");
Which tells that the content of the response is indeed XML and not html.

Unable to get json in correct format with file_get_contents()

I parse a parameter to a php file and try to get json with file_get_contents().
This is my Code:
< ?php
$url = $_GET['url'];
$url = urldecode($url);
$json = file_get_contents($url, true);
echo($json);
? >
This is the called URL:
http://vimeo.com/api/v2/channel/photographyschool/videos.json
This is a part of my result:
[{"id":40573637,"title":"All For Nothing - \"Dead To Me\" & \"Twisted Tongues\""}]
And so on... So everything is escaped. There are even \n in the result.
Since I neet to work afterwards with the json (in js), I need a non escaped version!
Interesting thing is, that my code works for example with this json:
http://xkcd.com/847/info.0.json
What is my problem?
If you just want to proxy/forward the response then just echo it as it is with the correct Content-Type header:
<?php
header('Content-Type: application/json');
$json = file_get_contents('http://vimeo.com/api/v2/channel/photographyschool/videos.json');
echo $json;
?>
Tho you have to be very wary of the url passed as it could cause XSS!
And as the API is slow/resource hungry you should cache the result or at least save it in a session so its not repeated on each page load.
<?php
$cache = './vimeoCache.json';
$url = 'http://vimeo.com/api/v2/channel/photographyschool/videos.json';
//Set the correct header
header('Content-Type: application/json');
// If a cache file exists, and it is newer than 1 hour, use it
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
echo file_get_contents($cache);
}else{
//Grab content and overwrite cache file
$jsonData = file_get_contents($url);
file_put_contents($cache,$jsonData);
echo $jsonData;
}
?>
Use this:
echo json_decode($json);
EDIT: FORGET the above. Try adding:
header('Content-Type: text/plain');
above
$url = $_GET['url'];
and see if that helps.
You should use json_decode :
http://php.net/manual/en/function.json-decode.php
better yet, where you deliver your json use:
json_encode(array(
"id" => 40573637,
"title" => 'All For Nothing - "Dead To Me" & "Twisted Tongues"'
));

NuSOAP 0.7.2 sending empty SOAP requests

OK, so before I get flooded with answers like "Use PHP's built-in SOAP extension" or "upgrade to nuSOAP 0.9.5" I just want to make it clear that these are not an option in my situation. I'm working in a hosted environment and I'm lucky they even had this legacy version of nuSOAP installed on the server.
That said, I need some help with my SOAP requests.
Here's what I have so far:
require_once('nusoap_0.7.2/nusoap.php');
ini_set("soap.wsdl_cache_enabled", "0");
date_default_timezone_set('America/Los_Angeles');
$wsdl = "https://api.bronto.com/v4?wsdl";
$ns = "https://api.bronto.com/v4";
$client = new soapclient($wsdl, array('trace'=>1, 'encoding'=>'UTF-8'));
// Login
$token = "API-TOKEN";
$sessionId = $client->call('login', array('apiToken' => $token), $ns, $ns);
if (!$sessionId) {
print "Login failed.\n";
exit;
}
print_r($sessionId);
$client->setHeaders(array($ns, 'sessionHeader', array('sessionId' => $sessionId)));
echo htmlspecialchars($client->request, ENT_QUOTES); // debug request
This is what the login call to the API returns:
Array ( [faultcode] => soap:Client [faultstring] => 107: There was an error in your soap request. Please examine the request and try again. [detail] => There was an error in your soap request. Please examine the request and try again. )
This is what the SOAP request ends up looking like:
POST /v4 HTTP/1.0 Host: api.bronto.com User-Agent: NuSOAP/0.7.2 (1.94)
Content-Type: text/xml; charset=UTF-8
SOAPAction: ""
Content-Length: 379
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns7166="https://api.bronto.com/v4">
<SOAP-ENV:Body>
<parameters/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The SOAP request appears to be sending fine but the envelope is empty. I suspect I may need to replace the arrays in the request with SoapVal objects, but the documentation on this object is difficult to get my head around.
For reference, this is the PHP SOAP code I am trying to translate to nusoap 0.7.2
ini_set("soap.wsdl_cache_enabled", "0");
date_default_timezone_set('America/New_York');
$wsdl = "https://api.bronto.com/v4?wsdl";
$url = "https://api.bronto.com/v4";
$client = new SoapClient($wsdl, array('trace' => 1, 'encoding' => 'UTF-8'));
$client->__setLocation($url);
// Login
$token = "ADD YOUR API TOKEN HERE";
$sessionId = $client->login(array("apiToken" => $token))->return;
if (!$sessionId) {
print "Login failed.\n";
exit;
}
$client->__setSoapHeaders(array(new SoapHeader("http://api.bronto.com/v4", 'sessionHeader', array('sessionId' => $sessionId))));
print "Login was successful.\n";
I had had same problem even on NuSOAP/0.9.11 and later. ;-) SOAPAction: ""
NuSOAP has several issues. E.g. it supports only wsdl-mode for me, and your NuSOAP api usage is wrong (new nusoap_client second parameter).
For using wsdl-mode you must smth like this:
$wsdlurl = 'https://api-sandbox.direct.yandex.com/v5/campaigns?wsdl'; // your wsdl url
$token = '<your token if needed>';
$locale = 'en';
// Construct NuSOAP-client
$client = new nusoap_client($wsdlurl, 'wsdl'); // second parameter must be boolean true or 'wsdl'
# Auth of NuSOAP-client
$client->authtype = 'basic'; /// but Yandex Direct needs 'bearer'
$client->decode_utf8 = 0;
$client->soap_defencoding = 'UTF-8';
// ..... $client->setCredentials and $client->setHeaders if needed
// Call soap/wsdl api method
$result = $client->call(
'get',
array('SelectionCriteria' => (object) array(), 'FieldNames' => array('Id', 'Name'))
); // string $operation (required), mixed $params (required), string $namespace (optional method namespace for non-WSDL), string $soapAction (optional SOAPAction value for non-WSDL)
// Output
echo "Request:<pre>".htmlspecialchars($client->request, ENT_QUOTES)."</pre>";
echo "Response:<p>".nl2br(htmlspecialchars($client->response, ENT_QUOTES))."</p>";
// Debug
echo '<hr><pre>'.htmlspecialchars($client->debug_str, ENT_QUOTES).'</pre>';
P.S.: If you need Yandex, fixed lib is here and samples client4yandex.

HttpRequest (PHP), how to post objects

code is as below:
<?php
//set up variables
$theData = '<?xml version="1.0"?>
<note>
<to>php.net</to>
<from>lymber</from>
<heading>php http request</heading>
<body>i love php!</body>
</note>';
$url = 'http://www.example.com/script.php';
//create the httprequest object
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
//add the content type
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
//add the raw post data
$httpRequest_OBJ->setRawPostData ($theData);
//send the http request
$result = $httpRequest_OBJ->send();
//print out the result
echo "<pre>"; print_r($result); echo "</pre>";
?>
Now httprequest calls the script here:
http://www.example.com/script.php
Over there I want to access the object, so that I can manipulate the data and send it back:
$httpRequest_OBJ->setRawPostData ($theData);
but it does not work. I tried $_POST['theData'], but this only works if you use $r->**addPostFields**(array('user' => 'mike', 'pass' => 's3c|r3t'));
How can I access the object $theData?
Thanks.
I think what you are after is php://input
So you can get the whole lot of XML that you posted like this:
$fp = fopen('php://input','r');
$data = '';
while (!feof($fp)) $data .= fread($fp,1024);
// $data should now contain the XML posted in your example
As a side note, I think the line
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
...should probably just read
$httpRequest_OBJ->setContentType = 'text/xml';

php - send and receive xml documents

I am trying to get a xml document back from the webserver that also supports php.
It's something similar to what the traditional web services do but i want to achieve it in php. Is this even possible?
To be more specific about my needs -
I want to send a xml document as a request to the server, have PHP do some processing on it and send me back an xml document as a response.
Thanks in advance.
Maybe you simply want http://php.net/SOAP ?
If not SOAP, then you can send your XML POST request and use $xml = file_get_contents('php://input'); to dump it to a variable that you can feed to http://php.net/DOM or other XML processors.
After processing, you header('Content-Type: text/xml'); (or application/xml) and output the modified XML document.
Super simple example of reading an XML request body:
$request = http_get_request_body();
if($request && strpos($request, '<?xml') !== 0){
// not XML do somehting appropriate
} else {
$response = new DomDocment(); // easier to manipulate when *building* xml
$requestData = DomDocument::load($request);
// process $requestData however and build the $response XML
$responseString = $response->saveXML();
header('HTTP/1.1 200 OK');
header('Content-type: application/xml');
header('Content-length: ', strlen($responseString));
print $responseString;
exit(0);
}
use curl.
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xmlString);
//execute post
$result = curl_exec($ch);

Categories