[英]PHP. Transferring downloaded csv to mysql database - how can I store downloaded csv file in php memory
I would like to store data downloaded from a website into my mysql database. 我想将从网站下载的数据存储到我的mysql数据库中。
I use my function "CallAPI("GET", $url, $data = false)" to access the database using a url such as " http://www.xflow1.com/xGlobalHist.csv/ "... 我使用函数“ CallAPI(“ GET”,$ url,$ data = false)“通过诸如” http://www.xflow1.com/xGlobalHist.csv/ “之类的URL访问数据库。
So my call $results = CallAPI($method, $url, $data = false); 所以我的电话$ results = CallAPI($ method,$ url,$ data = false); returns a comma delimted array that is saved in the variable "$results". 返回逗号分隔的数组,该数组保存在变量“ $ results”中。 I can echo $results in a web page and it show me the data, all comma delimited. 我可以在网页中回显$ results,它向我显示所有逗号分隔的数据。 All good `til here. 一切都好,直到这里。
To upload the csv to my mysql database I want to use the "LOAD DATA INFILE" function as so: 要将csv上传到我的mysql数据库,我想这样使用“ LOAD DATA INFILE”功能:
$upload = <<<eof
LOAD DATA INFILE $results
INTO TABLE X_Adjusted_All
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(Cusip, Date, Price)
eof;
The snag arises as "LOAD DATA INFILE $results" does not work as LOAD DATA INFILE only wants a filename, so I would like to store $results as a csv file in the memory to avoid creating and deleting files all the time. 出现此问题是因为“ LOAD DATA INFILE $ results”不起作用,因为LOAD DATA INFILE只需要一个文件名,因此我想将$ results作为csv文件存储在内存中,以避免一直创建和删除文件。 I thought this may work: 我认为这可能有效:
$fp = fopen('php://memory', 'w');
fputcsv($fp, $results);
Alas no. las Does anyone have any idea how to take the downloaded csv file and save it to the phps memory as a csv file for use in the LOAD DATA INFILE function? 有谁知道如何获取下载的csv文件并将其作为csv文件保存到phps内存中,以便在LOAD DATA INFILE函数中使用?
MySQL cannot read directly from PHP's memory. MySQL无法直接从PHP的内存中读取。 You need to create an external file using tempnam()
. 您需要使用tempnam()
创建一个外部文件。 That file can then be read by MySQL. 然后该文件可以由MySQL读取。 You could also create a temporary file and find out the filename as mentioned in this question . 您还可以创建一个临时文件并找出此问题中提到的文件名。
The example of tempnam()
shows how to write to that file: tempnam()
的示例显示了如何写入该文件:
<?php
$tmpfname = tempnam("/tmp", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, $results);
fclose($handle);
// do something
unlink($tmpfname);
This will store the contents of $results
to a file called $tmpfname
which you can store in mysql using LOAD DATA INFILE $tmpfname
. 这会将$results
的内容存储到名为$tmpfname
的文件中,您可以使用LOAD DATA INFILE $tmpfname
将其存储在mysql中。
As mentioned in the comments, you could create a ram drive to store that file, if performance is an issue. 如评论中所述,如果性能存在问题,则可以创建一个RAM驱动器来存储该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.