PHP下载独特的文件

时间:2015-12-29 10:03:25

标签: php xml file gpx

我正在尝试创建一个带有坐标的GPX文件,然后由用户下载。第一部分创建文件(工作正常)。但我似乎无法下载它。我希望这个文件是动态创建并下载的,这样当多个用户使用该服务时,他们的文件永远不会互换。

我认为我应该将数据放在变量而不是文件中,但这样我就可以测试它是否正常工作。

我是编码的新手,一定会犯错误;)

提前谢谢大家。

这是我到目前为止所拥有的;

<?php
// set_include_path("http://localhost/The%20Road%20Planner/tempMap/");
// $filename = uniqid('route.') . '.gpx';

$myfile = fopen('route.gpx', 'w') or die("Unable to open file!");


$route = (isset($_POST['RoutePath']) ? $_POST['RoutePath'] : null);


fwrite($myfile, '<?xml version="1.0" ?>' . '<gpx version="1.0" creator="Fabrication Junkies" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/0" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">' . PHP_EOL . '<trk>' . PHP_EOL .
 '<name>Map</name>' . PHP_EOL . '<trkseg>'.PHP_EOL);

$coordinates = json_decode($route, true);


foreach($coordinates as $pair) {
  $output = '<trkpt lat="' . $pair['lat'] .'" lon="'. $pair['lng'] . '"></trkpt>' . PHP_EOL;
  fwrite($myfile, $output);
}

fwrite($myfile, '</trkseg>' . PHP_EOL . '</trk>' . PHP_EOL . '</gpx>');
fclose($myfile);

 header("Content-type: application/gpx+xml");
 header("Content-Disposition: attachment;Filename=route.gpx");

 echo "<xml>";
// your gpx data here
$myfile
 echo "</xml>";
?>

2 个答案:

答案 0 :(得分:0)

如果您需要在同一目录中创建文件并且不想混合名称,可以使用uniqid()函数创建唯一的文件名,例如

// preparing unique file name with time prefix
$prefix = uniqid(); // generates a uniqueId based on the microtime
$filePath = $prefix . "_route.gpx";

// opening and writing data inside
$myfile = fopen($filePath, 'w');
... fwrite() what you need inside
fclose($myfile);

// out as download
header("Content-type: application/gpx+xml");
header("Content-Disposition: attachment;Filename=route.gpx");

readfile($filePath);

您可以在此处详细了解php uniqid() - http://www.w3schools.com/php/func_misc_uniqid.asp

答案 1 :(得分:0)

您必须为文件创建不同的名称。您可以将SESSION_ID添加到filename:

<?php
$filename = session_id().'route.gpx';
$myfile = fopen($filename, 'w') or die("Unable to open file!");
?>

如果用户已登录,您可以在文件名中添加用户ID:

<?php
$filename = $user_id.'route.gpx';
?>