【问题标题】:Parsing csv where the last "header" is followed by a space解析csv,其中最后一个“标题”后跟一个空格
【发布时间】:2017-06-07 13:49:05
【问题描述】:

我正在尝试以下列方式使用str_getcsv 解析 csv,但是我遇到了两个问题(如下)。

$url = 'http://my.events.calendar/api/csv?mycalendarquery';
$response = wp_remote_get($url);
$response_body = $response['body']; // this is a really long string
$parsed_string = str_getcsv($response_body, ',', '"');
$full_events_array = array_chunk($parsed_string, 11);

问题 1 - 我不能使用 explode,因为 csv 中的字段之一是 "Description",其中包含许多/冗长的事件散文描述。当然,这些包括逗号、换行符、回车符等......

问题 2 - 这是我有一个问题。 csv 文件的类别(标题?)是"Subject", "Date", (more things here...) "Description", "Calendar Address"。但是最后一个后面没有逗号。所以,"Subject""Calendar" 地址的条目是这样组合的 -

array(11) {
  [0] =>
  string(32) "Calendar Address
  "Application Due"" // this pattern happens for every event but with a url instead.
// Yes, I know this looks wrong in the code block, but this is exactly how the data is coming in (complete with the double quotes).

如何解析这个,以便将Calendar AddressApplication Due 分开?

作为参考,我还尝试了str_getcsv($response_body, '"', ',');str_getcsv($response_body, ',', '"', '\n'); 和其他几种组合。感谢您的帮助!

【问题讨论】:

  • 您能否发布一个带有测试数据链接的 URL?谢谢。
  • Test Data - 谢谢@RayPaseur。这就是饲料的来源。对不起。更新了网址。我在尝试不同的方法。
  • 感谢您发布链接。这是一个有效的 CSV 文件,即使它看起来很奇怪。
  • 这不是应该这样传输的数据;那应该是 RDF 或 XML 或 JSON。如果他们提供其他提要,我会考虑的。
  • 我可能会尝试使用此 Calendar File Parser 的 vCal 版本。不过,不知道它是否支持具有多个条目的 vCal。

标签: php csv parsing


【解决方案1】:

此脚本会将 CSV 文件读入 251 行,每行 12 个元素。

<?php // demo/temp_44414553.php
/**
 * https://stackoverflow.com/questions/44414553/parsing-csv-where-the-last-header-is-followed-by-a-space?noredirect=1#comment75830321_44414553
 */
error_reporting(E_ALL);

// UNABLE TO ACCESS: http://events.uconn.edu/exports-2017-05-31-2017-07-01.csv
// COPY MADE HERE FROM THE DOWNLOAD LINK
$url = 'storage/exports-2017-05-31-2017-07-01.csv';
$csv = file_get_contents($url);
echo $csv;

$fpr = fopen($url, 'r');
if (!$fpr) trigger_error("Unable to open $url", E_USER_ERROR);

$kount = 0;
while (!feof($fpr))
{
    $row = fgetcsv($fpr);
    $kount++;
    if (!$row) break;
    echo PHP_EOL . count($row);
}

echo PHP_EOL . "There are $kount rows in the CSV at $url";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多