我有一个PHP方法,返回json字符串如下:
function getjson(){
$mun = $this->input->POST('municipality');
$sl = $this->input->POST('saleslimit');
$q = $this->db->query("SELECT RollNum , Address, v2_lat, v2_lng
FROM tblontario WHERE Municipality = '".$mun."'"." LIMIT ".$sl);
$json_string = json_encode($q->result(), JSON_PRETTY_PRINT);
file_put_contents('/home/apts/Dropbox/ptax.ca/js/salecomps.json', $json_string);
echo $json_string;
}
而不是返回一个json字符串,我希望能够返回一个CSV文件,这样我就可以把这个CSV文件,并以某种方式把它变成一个geojson
文件,可以加载到谷歌地图。
关于如何实现这一点有什么想法吗?我的最终目标是创建一个geojson
文件,但我不确定最好的方法是什么。谢谢。
如果$row是一个数组,你可以这样做:
function getCSV() {
$mun = $this->input->POST('municipality');
$sl = $this->input->POST('saleslimit');
$q = $this->db->query("
SELECT
RollNum,
Address,
v2_lat,
v2_lng
FROM
tblontario
WHERE
Municipality = '".$mun."'"."
LIMIT ".$sl
);
$row = $q->result();
$csvRow = implode(",",$row);
file_put_contents('/home/apts/Dropbox/ptax.ca/js/salecomps.csv', $csvRow);
echo $csvRow;
}
因为我在那里看到了一个限制,我猜你得到了不止一个结果,$q->result();在这种情况下,返回结果的数组而不仅仅是一行,
function getCSV() {
$mun = $this->input->POST('municipality');
$sl = $this->input->POST('saleslimit');
$q = $this->db->query("
SELECT
RollNum,
Address,
v2_lat,
v2_lng
FROM
tblontario
WHERE
Municipality = '".$mun."'"."
LIMIT ".$sl
);
$res = $q->result();
if(!empty($res)){
$fh = fopen('/home/apts/Dropbox/ptax.ca/js/salecomps.csv','w');
foreach($res as $row){
// as suggested by @GigaWatt, swapped fwrite for fputcsv
fputcsv($fh,$row);
}
fclose($fh);
echo file_get_contents('/home/apts/Dropbox/ptax.ca/js/salecomps.csv');
} else {
echo "";
}
}
编辑:看一个GeoJSON规范,你可能想要的东西是:
function getGeoJSON() {
$mun = $this->input->POST('municipality');
$sl = $this->input->POST('saleslimit');
$q = $this->db->query("
SELECT
RollNum,
Address,
v2_lat,
v2_lng
FROM
tblontario
WHERE
Municipality = '".$mun."'"."
LIMIT ".$sl
);
$res = $q->result();
if(!empty($res)){
$geoArr = Array(
"type" => "MultiPoint",
"coordinates" => Array()
);
foreach($res as $row) {
$geoArr["coordinates"][] = Array($row['v2_lat'],$row['v2_lng']);
}
$geoJSON = json_encode($geoArr);
file_put_contents('/home/apts/Dropbox/ptax.ca/js/salecomps.geojson',$geoJSON);
echo $geoJSON;
} else {
echo "{}";
}
}
据我所知,您基本上是在寻找getCSV()函数。您可以通过手动连接结果集的元素来实现这一点。像这样。
function getCSV(){
$mun = $this->input->POST('municipality');
$sl = $this->input->POST('saleslimit');
$q = $this->db->query("SELECT RollNum , Address, v2_lat, v2_lng FROM tblontario WHERE Municipality = '".$mun."'"." LIMIT ".$sl);
$row = $q->result();
$csvString = $row->{'RollNum'}.','.$row->{'Address'}.','.$row->{'v2 lat'}.','.$row->{'v2 lng'};
file_put_contents('/home/apts/Dropbox/ptax.ca/js/salecomps.csv', $csvString);
echo $csvString;
}