0

php send pdf file in curl response

My curl request :

request.php

$post = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<request>   
    <stmt_no>123456</stmt_no>
    <from_date>01/05/2023</from_date>
    <to_date>18/05/2023</to_date>   
</request>';

$target_url = "http://example.com/stmt/Api.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HEADER, 'Content-Type: text/xml');

$result=curl_exec($ch);
$info = curl_getinfo($ch);
curl_close ($ch);

now at Api.php, i am receiving these data stmt_no, from_date, to_date and depending on this input i am generating pdf file say xyz.pdf

and i am responding below xml :

<?xml version="1.0" encoding="utf-8"?>
<response>
<stmt_no>123456</stmt_no>
<pdfContent>file_get_contents('xyz.pdf')</pdfcontent>

now at request.php when i am trying to parse response xml with $x1=simplexml_load_string($result);

i am getting below error

Warning: simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found in...

My goal is to send pdf in response and save the same file

  • 1
    Does this answer your question ? (or provide a good hint ? ) [Making PHP curl request to Download PDF using API url](https://stackoverflow.com/questions/26270278/making-php-curl-request-to-download-pdf-using-api-url) – Ken Lee May 18 '23 at 15:15
  • Check the XML being returned. Make sure to remove any no printable characters. – Jason K May 18 '23 at 15:53
  • 1
    @JasonK , of course there will be "no printable" character as i am using file_get_contents('xyz.pdf') –  May 18 '23 at 15:57
  • 1
    Usually to include binary data in an XML file (or similar) you'd [base64 encode](https://stackoverflow.com/q/19893/231316) it – Chris Haas May 18 '23 at 16:52
  • base64_encode(file_get_contents('xyz.pdf')) did the trick –  May 19 '23 at 09:48

0 Answers0