php - send and receive xml documents - php

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);

Related

How to get a webpage containing an external API in php

I have a php script that loads this webpage to extract some data from it's tables.
The following methods failed to get it's table contents:
Using file_get_contents:
$document -> file_get_contents("http://www.webpage.com/");
print_r($document);
Using cURL:
$document = curl_init('http://www.webpage.com/');
curl_setopt($document, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($document);
print_r($html);
Using loadHTMLFile:
$document->loadHTMLFile('http://www.webpage.com/');
print_r($document);
I'm not an expert in php and except the first method, the other ones are copied from StackOverflow's answers.
What am I doing wrong?
and How they do block some contents from loading?
Not the answer you're likely to want to hear, but none of the methods you describe will evaluate JavaScript and other browser resources as a normal browser client would. Instead, each of those methods retrieves the contents of only the file you've specified. A quick glance at the site you're targeting clearly shows this table in question being populated as the result of an AJAX call, which none of the methods you've tried are able to evaluate.
You'll need to lean on a library or script that has the capability for this type of emulation; namely laravel/dusk, the PHP bindings for Selenium webdriver, or something similar.
This is what I did to scrape data from a webpage using php curl:
// Defining the basic cURL function
function curl($url) {
$ch = curl_init(); // Initialising cURL
curl_setopt($ch, CURLOPT_URL, $url); // Setting cURL's URL option with the $url variable passed into the function
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Setting cURL's option to return the webpage data
$data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
curl_close($ch); // Closing cURL
return $data; // Returning the data from the function
}
// Defining the basic scraping function
function scrape_between($data, $start, $end){
$data = stristr($data, $start); // Stripping all data from before $start
$data = substr($data, strlen($start)); // Stripping $start
$stop = stripos($data, $end); // Getting the position of the $end of the data to scrape
$data = substr($data, 0, $stop); // Stripping all data from after and including the $end of the data to scrape
return $data; // Returning the scraped data from the function
}
$target_url = "https://www.somesite.com";
$scraped_website = curl($target_url);
$data_set_1 = scrape_between($scraped_website, "%before%", "%after%");
$data_set_2 = scrape_between($scraped_website, "%before%", "%after%");
The %before% and %after% is data that always shows up on the webpage before and after the data you wish to grab. Could be div tags or some other html tags that are unique to the data you wish to grab.
So maybe look into using curl and and imitate the same ajax request that the site is using? When I searched for that, this is what I found:
Mimicking an ajax call with Curl PHP

The client API want me to reply back with a xml

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'?>";

PHP - Encoding issue when saving to XML file using SimpleXml

I am struggling with encoding issues in a PHP app that:
Reads an XML file and parses it according to some rules
Calls the Google Translate API and uses the result to populate a
database that is later used to display data on the browser (that
part works well)
Saves that data to an XML file (it saves but there's something wrong
with the encoding).
The data comes from Google Translate encoded in UTF-8 and in the browser, provided that you have the proper heading it displays fine whatever the language is.
Here's the Google Translate function:
function mt($text, $lang) {
$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=' . $lang;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, JSON_UNESCAPED_UNICODE);
$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if($responseCode != 200) {
$resultxt = 'not200result';
}
else {
$resultxt = $responseDecoded['data']['translations'][0]['translatedText'];
}
return $resultxt;
}
I'm using Simplexml to load an XML file, modify its contents and save it with asXml().
The generated XML file is encoded in something other than UTF-8 as it looks like this:
<value>ようこそ%0 ST数学</value>
Here's the code that attributes the translation to the XML node and saves it.
$xml=simplexml_load_file('myfile.xml'); //Load source XML file
$xml->addAttribute('encoding', 'UTF-8');
$xmlFile = 'translation.xml'; //File that will be saved
//Here I have a call to the MT function above and get it to the XML file at face value.
$xml->asXML($xmlFile) //save translated XML file
I've tried using htmentities() and played with utf8_encode() and utf8_decode() but can't make it work.
I've tried everything and looked at many other posts. For the life of me, I can't figure this one out. Any help is appreciated.

php, curl, headers and content-type

I am having some trouble working with curl and headers returned by servers.
1) My php file on my_website.com/index.php looks like this (trimmed version):
<?php
$url = 'http://my_content_server.com/index.php';
//Open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result;
?>
The php file on my_content_server.com/index.php looks like this:
<?php
header("HTTP/1.0 404 Not Found - Archive Empty");
echo "Some content > 600 words to make chrome/IE happy......";
?>
I expect that when I visit my_website.com/index.php, I should get a 404, but that is not happening.
What am I doing wrong?
2) Basically what I want to achieve is:
my_content_server.com/index.php will decide the content type and send appropriate headers, and my_website.com/index.php should just send the same content-type and other headers (along with actual data) to the browser. But it seems that my_website.com/index.php is writing its own headers? (Or maybe I am not understanding the working correctly).
regards,
JP
Insert before curl_exec():
curl_setopt($ch,CURLOPT_HEADER,true);
Instead of just echo'ing the result, forward the headers to the client as well:
list($headers,$content) = explode("\r\n\r\n",$result,2);
foreach (explode("\r\n",$headers) as $hdr)
header($hdr);
echo $content;

How to redirect a live data stream adding to it another header and returning it on demand? (PHP)

I have a url like http://localhost:8020/stream.flv
On request to my php sctipt I want to return (be something like a proxy) all data I can get from that URL (so I mean my php code should get data from that url and give it to user) and my header and my beginning of file.
So I have my header and some data I want to write in the beginning of response like
# content headers
header("Content-Type: video/x-flv");
# FLV file format header
if($seekPos != 0)
{
print('FLV');
print(pack('C', 1));
print(pack('C', 1));
print(pack('N', 9));
print(pack('N', 9));
}
How to do such thing?
Here's the code I used to do something very similar, I also forwarded all headers from the original flv to the end user but you can just remove that section if you want to set your own.
$video = fopen(URL, "rb");
// Forward headers, $http_response_header is populated by fopen call
foreach ($http_response_header AS $header) {
header($header);
}
// Output contents of flv
while (!feof($video)) {
print (fgets($video));
}
fclose($video);
See the manual entries for fopen and fread.
I've accomplished this using libcurl,
$url = 'http://localhost:8020/stream.flv';
$ch = curl_init();
curl_exec($ch);
curl_close($ch);

Categories