我有一个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;
}
我希望能够返回一个CSV文件,而不是返回一个json字符串,以便我可以将该CSV文件转换为geojson
文件,该文件可以加载到{{ 3}}。
关于如何实现这一目标的任何想法?最终我的目标是创建一个geojson
文件,但我不确定最好的方法。感谢。
答案 0 :(得分:1)
据我所知,您基本上在寻找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;
}
答案 1 :(得分:1)
如果$ 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 "{}";
}
}