如何从Google App Engine下载CSV文件?

时间:2019-01-11 10:31:19

标签: google-app-engine mysqli google-cloud-platform

我无法从Google App Engine下载文件。这在Compute Engine中运作。

$sql="SELECT * FROM $table ";

$query = $db->runQuery($sql);

if($query->num_rows > 0) {
    $delimiter = ",";
    $filename = $table . date('Y-m-d') . ".csv";  

    // create a file pointer
    $f = fopen('php://memory', 'w');

    // set column headers
    $fields = array('id', 'srno', 'empid', 'empname');
    fputcsv($f, $fields, $delimiter);

    // output each row of the data, format line as csv and write to file pointer
    while($row = $query->fetch_assoc()) {
        // $status = ($row['status'] == '1') ? 'Active' : 'Inactive';
        $lineData = array(
            $row['id'], $row['srno'], $row['empid'], $row['empname'], ]
        );
        fputcsv($f, $lineData, $delimiter);
    }

    // move back to beginning of file
    fseek($f, 0);

    // set headers to download file rather than display it
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');

    //output all remaining data on a file pointer
    fpassthru($f);
}
exit;

1 个答案:

答案 0 :(得分:0)

什么是日志,错误消息?您是如何部署此应用的?您可以显示app.yaml吗?该应用程序是否与Cloud SQL实例位于同一项目中?标准还是灵活的环境? PHP 5或7?

将App Engine连接到Cloud SQL时最常见的问题:

  • App Engine服务帐户必须具有Cloud SQL Admin角色
  • Cloud SQL实例所在的项目必须同时激活Cloud SQL和SQL Admin API
  • 应用程序与MySQL实例之间的连接是通过代理完成的,代理是在php代码和yaml文件中配置的。

这里是从PHP72连接到MySQL实例的示例,您也可以使用此代码进行本地测试。为此,您将需要install and run the Cloud SQL Proxy Client

app.yaml

runtime: php72

handlers:
- url: .*
  script: auto

env_variables:
  MYSQL_USER: [MYSQL_USER]
  MYSQL_PASSWORD: [MYSQL_PASSWORD]
  MYSQL_DSN: 'mysql:dbname=[MYSQL_DB_NAME];unix_socket=/cloudsql/[MYSQL_INSTANCE_CONNECTION_NAME]'

beta_settings:
  cloud_sql_instances: [MYSQL_INSTANCE_CONNECTION_NAME]

index.php

<?php
    $user = getenv('MYSQL_USER');
    $password = getenv('MYSQL_PASSWORD');
    $dsn = getenv("MYSQL_DSN") ?: "mysql:host=127.0.0.1;port=3306;dbname=[MYSQL_DB_NAME]";

    $db = new PDO($dsn, $user, $password);

    try {
        $db = new PDO($dsn, $user, $password);

        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully"; 
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }

    $statement = $db->prepare("SELECT * from [MYSQL_TABLE_NAME]");
    $statement->execute();
    $all = $statement->fetchAll();

    foreach ($all as $data) {
      echo $data["id"];
    }
?>