【问题标题】:Send pdf from wp_remote_get to browser将 pdf 从 wp_remote_get 发送到浏览器
【发布时间】:2017-08-18 18:35:16
【问题描述】:

我正在将 wordpress 网站与外部 API 集成。我有一个发布到我的服务器的表单,我在我的服务器上调用一个函数,该函数对外部 API 进行 wp_remote_get 调用。

外部 API 返回一个 PDF,标题如下:

        [date] => Fri, 18 Aug 2017 15:59:19 GMT
        [x-powered-by] => Servlet/3.0
        [cache-control] => no-cache
        [content-type] => application/pdf;charset=utf-8
        [content-language] => en-US

响应正文是讨厌的字符串格式的 PDF,这似乎是一个好的开始。

如何将此 PDF 传递到用户的浏览器? 即,

$response = wp_remote_get( $url, array ( //stuff the request needs));
if (is_wp_error ($response)) {
    $error_message = $response->get_error_message();
    echo "Something went wrong: $error_message";
} else {
    //What here?
}

我必须先访问我的服务器,无法将表单直接发布到外部 API。

【问题讨论】:

    标签: wordpress pdf


    【解决方案1】:

    我通过使用 javascript 将我的表单提交重定向到我网站上的新窗口来管理这一点,并将表单信息作为 URL 参数传递。 IE, 在我的 HTML 中:

    <form onsubmit="return qrsDownload()">
    

    然后在javascript中:

    function qrsDownload() {
        // a bunch of jquery and processing to build the URL..
        window.open(url, 'My Title', 'width=800, height=600');
    }
    

    我打开的页面是我创建的一次性页面模板,我在该页面的 php 文件中省略了标准 WP 模板(因此没有页眉、页脚和 wordpress 循环):

    <?php 
    if (isset($_GET['someParam'])) {
      // started off with logic to verify that I had the params needed
      // because anybody could just jump directly to this page now
    }
    $url = "whateverurl.com/myendpoint";
    // additional logic to set up the API call
    $server_response = wp_remote_get($url, $args);
    if (is_wp_error( $server_response) ) {
        // do something to handle error
    } else {
        // PASS OUR PDF to the user
        $response_body = wp_remote_retrieve_body( $server_response);
        header("Content-type: application/pdf");
        header("Content-disposition: attachment;filename=downloaded.pdf");
        echo $response_body;
    }
    } else {
         get_header();
        $html = "<div class='content-container'><p>A pretty error message here.</p></div>";
         echo $html;
         get_footer();
    }
    
    ?>
    

    该方法本质上是将 API 的结果直接传回给用户,但是您需要标头来指定它是 PDF,并且必须在写出任何输出之前设置标头。确保这一点的更简单方法是在新窗口中执行此操作,而不是严格在表单回发上。

    【讨论】:

      猜你喜欢
      • 2010-10-18
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多