简体   繁体   中英

Parse string as CSV with PHP

I'm doing an API request that returns me a really long string in CSV format. Here's two lines:

Backup ID,Account,Account Number,Snapshot Account,Snapshot Account Number,Policy,Status,Region,Type,Volume/DB/Cluster,Volume/DB/Cluster Name,Instance,Instance Name,Snapshot ID,Succeeded,Start Time,End Time,Deleted At,Volume Size (GB),Valid Data Size (GB),Changed Data Size (GB)
1542,Account Goes Here,Account Nmber Goes Here,Snapshot Account Goes Here,Snapshot Account Number Goes Here,Policy Goes Here,All Snapshots Deleted,Region Goes Here,Type Goes Here,Volume Goes Here,Volume Name Goes Here,Instance Goes Here,Instance Name Goes Here,Snapshot ID Goes Here,Yes,06/15/2020 06:00:35 PM,06/15/2020 06:02:18 PM,06/22/2020 06:27:18 PM,Volume Size Goes Here,N/A,Unknown
1542,Account Goes Here,Account Nmber Goes Here,Snapshot Account Goes Here,Snapshot Account Number Goes Here,Policy Goes Here,All Snapshots Deleted,Region Goes Here,Type Goes Here,Volume Goes Here,Volume Name Goes Here,Instance Goes Here,Instance Name Goes Here,Snapshot ID Goes Here,Yes,06/15/2020 06:00:35 PM,06/15/2020 06:02:18 PM,06/22/2020 06:27:18 PM,200,N/A,Unknown

I want to parse this string and place it in an array.

The size of this string can vary since it is generated each day.

How can I achieve this?

try this

$f = file(...your csv file...);
foreach($f as $k => $line) {
    if ($k > 0) //we skip the first one
    {
        $results = explode(',', $line);
        //at this stage $results is a flat array
        // var_dump($result);
        ... do your stuff...
    }
}

I resolved my problem using the following code:

function treatString() {
    // Parsing the string as array
    $lines = explode(PHP_EOL, $string);
    $reports = array();
    foreach ($lines as $line) {
        $reports[] = str_getcsv($line);

        // doing something then...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM