0

我有一个数组“$results”,其中包含使用正则表达式从网页中抓取的结果集。我在遍历数组以将数组的整个数据写入 .csv 文件时有点困惑。

这是按以下方式打印后的数组输出。

print_r ($results);    //printing the array

输出

 Array
    (
        [fullName] => Ogdensburg Walmart Store #2092
        [street1] => 3000 Ford Street Ext
        [city] => Ogdensburg
        [state] => NY
        [zipcode] => 13669
        [phone] => (315) 394-8990
        [latitude] => 44.7083
        [longitude] => -75.4564
    )
    Array
    (
        [fullName] => Evans Mills Walmart Supercenter Store #5497
        [street1] => 25737 Us Route #11
        [city] => Evans Mills
        [state] => NY
        [zipcode] => 13637
        [phone] => (315) 629-2124
        [latitude] => 44.0369
        [longitude] => -75.8455
    )
    Array
    (
        [fullName] => Watertown Walmart Supercenter Store #1871
        [street1] => 20823 State Route 3
        [city] => Watertown
        [state] => NY
        [zipcode] => 13601
        [phone] => (315) 786-0145
        [latitude] => 43.9773
        [longitude] => -75.9579
    )

我只使用过简单的数组,谁能给我提示如何遍历$results数组以将其写入 .csv 文件或 .xls 文件。

4

3 回答 3

2
$fp = fopen($filename, 'w');
foreach ($results as $row) {
   fputcsv($fp, $row);
}
于 2012-06-03T15:38:24.780 回答
1

嗨,

尝试使用 parseCSV 类,http://www.coursesweb.net/php-mysql/parsecsv_pc

可以轻松读取 CSV 数据,也可以将二维数组转换为 CSV。

于 2012-06-03T14:03:47.883 回答
1

你可以使用这个:

$fp = fopen("file.csv","w");
foreach((array)$results as $val) {
   fwrite($fp,implode(";",$val)."\r\n");
}
fclose($fp);

有几件事要说:

  • 需要"\r\n"正确更改线路

  • 虽然最常见的分隔符是逗号(,),但我发现一些应用程序(如 microsoft excel 2010)不喜欢它,而是put the whole line in a cell;而不是semicolon在这种情况下工作。

  • 我总是遇到fputcsv问题,所以我选择了这个。

编辑:

    $fp = fopen("file.csv","w");
    $contents = file_get_contents('http://www.walmart.com/storeLocator/ca_storefinder_results.do?serviceName=&rx_title=com.wm.www.apps.storelocator.page.serviceLink.title.default&rx_dest=%2Findex.gsp&sfsearch_single_line_address=K6T');
    preg_match_all('/stores\[(\d+)\] \= \{/s', $contents, $matches);        
    foreach ($matches[1] as $index) {       
        preg_match('/stores\[' . $index . '\] \= \{(.*?)\}\;/s', $contents, $matches);
        preg_match_all('/\'([a-zA-Z0-9]+)\' \: ([^\,]*?)\,/s', $matches [1], $matches);
        $c = count ($matches [1]);
        $results = array();
        for ($i=0; $i<$c; $i++)  {
            $results [$matches [1] [$i]] = trim($matches [2] [$i], "\'");
        }
        fwrite($fp,implode(";",array_values($results))."\r\n");
    }
    fclose($fp);

编辑2:

要写入only specific columns.csv 文件,您需要避免将它们添加到结果数组()中在之后取消设置它们,如下所示:

...
for ($i=0; $i<$c; $i++)  {
    $results [$matches [1] [$i]] = trim($matches [2] [$i], "\'");
}
unset( $results["weekEndSaturday"] );
unset( $results["recentlyOpen"] );
.. go on, renove the non-desired values ..
fwrite($fp,implode(";",array_values($results))."\r\n");
于 2012-06-03T14:04:23.973 回答