fgetcsv 忽略来自网站但不是本地的 csv

fgetcsv ignores csv from website but not local

我正在编写一个脚本来访问一个网站,该网站将 csv 下载到缓存中,然后将数据解析为一个数组。

 $base_url = "http://www.collincad.org/ccad/propertysearch/download.php?situs_num=1707&situs_street=university&situs_street_suffix=&isd%5B%5D=any&city%5B%5D=any&prop_type%5B%5D=R&prop_type%5B%5D=P&prop_type%5B%5D=MH&active%5B%5D=1&year=2018";

$handle = fopen($base_url, "r");
$flag = true;  
while(!feof($handle))
{
  $text = fgetcsv($handle, 1024, ",");
   if($flag) { $flag = false; continue; }

   print $text[1]. " <br>";
}

mysql_close($connect);

以这种方式执行查询时,它具有第一行和一行其他数据,并忽略逗号。

 $base_url = "export5.csv";

 $handle = fopen($base_url, "r");
 $flag = true;  
 while(!feof($handle))
 {
  $text = fgetcsv($handle, 1024, ",");
   if($flag) { $flag = false; continue; }

   print $text[1]. " <br>";
}

mysql_close($connect);

但是当我手动下载 csv 文件并从本地文件夹中读取它时,它按预期工作...我不想将其分为两步过程...我认为直接从网站读取php 是问题所在,刚好可以找出解决方法。

谢谢

首先也是最重要的是,在将 fopen 与网络 url 一起使用时,请确保您的服务器配置为允许它 (http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen)。一旦解决了这个问题,您的代码就应该没问题了。

问题是 CSV 格式本身。

查看 url 的 CSV return,它的分隔符是制表符,而不是逗号。而且我也没有看到任何外壳。因此,您需要将 fgetcsv 更改为:

$text = fgetcsv($handle, 1024, "\t", '');

它应该开始 return 这样的结果(对于每个 $text):

Array
(
    [0] => 15071
    [1] => 2018
    [2] => P
    [3] => Personal
    [4] => P-9000-288-0243-1
    [5] => N
    [6] => ZZZZZZZ BPP @ 1707 W UNIVERSITY DR
    [7] => 
    [8] => 
    [9] => 
    [10] => 
    [11] => 
    [12] => BPP AT 1707 W UNIVERSITY DR
    [13] => KROGER #488
    [14] => 1707
    [15] => UNIVERSITY DR
    [16] => MCKINNEY
    [17] => 1707 W University Dr | McKinney, TX  75069
    [18] => 844925
    [19] => THE KROGER CO
    [20] => CMC
    [21] => MCKINNEY CITY
    [22] => SMC
    [23] => MCKINNEY ISD
    [24] => 
    [25] => Active
    [26] => No
    [27] => 
)

还有,csv文件的第一行是这样的:

第 1 行:

Array
(
    [0] => sep=
    [1] => 
)

所以您可能想跳过前两行(第二行是 headers 列)。

第 2 行:(第 headers 列)

Array
(
    [0] => Property ID
    [1] => Year
    [2] => Property Type Code
    [3] => Property Type Description
    [4] => Geographic ID
    [5] => Abstract Or Subdivision Code
    [6] => Abstract Or Subdivision Description
    [7] => Block
    [8] => Tract Or Lot
    [9] => Mobile Home Park Code
    [10] => Mobile Home Park Description
    [11] => Mobile Home Park Space
    [12] => Legal Description
    [13] => Doing Business As
    [14] => Street Number
    [15] => Street Name
    [16] => City
    [17] => Complete Address
    [18] => Owner ID
    [19] => Owner Name
    [20] => Taxing City Code
    [21] => Taxing City Name
    [22] => Taxing School District Code
    [23] => Taxing School District Name
    [24] => Market Value
    [25] => Property Status
    [26] => Certified Data
    [27] => 
)