bart2puck
bart2puck

Reputation: 2522

php read file from api call

I am connecting to a 3rd party's API service to get a list of files attached to a given ticket. One of the calls is get_attachment.

 call($client,'get_attachment',$data);

$client and $data are just info about connection and filename, etc...

the result is the actual file itself. if i print_r(call(....)), i get the file itself in my browser window. How can i present this to a user to download from my page? I would like to provide a hyper link, so the user can choose to click link and download this file.

  foreach ($attachments as $id => $fileName){
        echo "<a href='???'>".$fileName."</a>";
  }

If i need to save the file locally that is fine, how would i go about referencing this file??

This is the only note i have for the 3rd party's api related to this call:

"This method will output file data for the specified attachment."

Upvotes: 0

Views: 966

Answers (1)

simandsim
simandsim

Reputation: 202

One approach to solving this is by calling the API on two separate requests, once to get the list, and another to download the file.

If your listing page ended up like the below, it would show the attachments, and clicking the link would open the attachment on a new tab and download the file

// include this at the top of your file before any other HTML is rendered.
if (isset($_GET['file')) {
    // assuming $data will contain some reference to the filename now stored in $_GET['file']
    echo call($client,'get_attachment',$data);
    return;
}

// assuming $attachments contains the list of the files
foreach ($attachments as $id => $fileName){
    echo "<a href='thisPage.php?file=" . $fileName . "'>" . $fileName . "</a>";
}

So your link ends up linking to the same page, but rather than rendering any HTML once someone clicks the link at the top of your script you would make the API call to get the file contents and then terminate the script (either return or exit will do the trick) - assuming you can call the contents of the file by its file name.

You may need to pass more than the filename, maybe the id? Whatever you need to make the API call for the attachment, you can pass through on the link.

Upvotes: 1

Related Questions