提高页面性能,在服务器上保存PHP数组?

是否可以将PHP数组存储到我的服务器,现在它总是在有人从CSV文件重新加载页面时创建,但这是不必要的,因为文件只在每小时之后发生。

ATM,页面加载需要9秒钟,这很长。 CSV文件有10k +行,每行9个元素,因此如果服务器不必为每个用户处理100k元素,那么性能确实很好。

我已经有一个用于下载csv文件的cronjob,所以如果在下载完成后执行parse命令,每小时只执行一次,那将会很好。

的cronjob:

<?php function download_remote_file($file_url, $save_to) { $content = file_get_contents($file_url); file_put_contents($save_to, $content); } download_remote_file(, realpath(".") . '/dump.csv'); ?> 

and this happens with every reload of the page:

1st: Parse data to array

 $url = 'dump.csv'; $csvData = file_get_contents($url); $lines = explode(PHP_EOL, $csvData); $array = array(); foreach ($lines as $line) { $line = str_replace("\\", "\", $line); $line = str_replace("#", "#", $line); $array[] = str_getcsv($line); 

2nd: pass array to Javascript

 var array = ; 

3rd: create HTML table

 //some code 

4th: initialise data table plugin

 $(document).ready( function () { createtable(); $('#scoreboard').DataTable( { "iDisplayLength": 50, language: { decimal: ".", }, "lengthMenu": false, "bLengthChange": false } ); } ); 

Is there something that could be done faster?

Like, as mentioned, save the php array server-side or maybe saving the JS array with the HTML table somehow?

-Innerwolf

Since you mention getting the data on an hourly basis I suggest the following:

  1. grab the CSV file with cron and store the data in a database on an hourly basis
  2. configure your data tables component to use server side data

This way you won’t force every user to download the entire array at once on every first page load. The server side script only fetches the number of records that need to be displayed on that particular page in the table.

After you parse your CSV, do this:

 $file = fopen('/tmp/output.js', 'w'); fwrite($file, ''); fclose($file); copy('/path/to/script.js', '/path/to/script.js.bak'); move('/tmp/output.js', '/path/to/script.js'); 

Then, later on when you are outputting the HTML, you just need to stick in a:

  

in the header. People's browsers should cache it properly too. Note the copy and move -- you don't strictly need to make a backup copy, but you MUST use a move() to replace the 'live' script -- move() is atomic, more or less, and won't result in anyone getting a half-file.

Also, note that you'll need write permissions to where the script is -- there are ways to keep this pretty secure (not letting your PHP script write all over the hard drive), but that's out of scope here.

Interesting Posts