|
| 1 | +<?php |
| 2 | + |
| 3 | +echo "\n\n"; |
| 4 | +echo "Run asana-json2csv.php...\n\n"; |
| 5 | + |
| 6 | +if (php_sapi_name() !== 'cli') { |
| 7 | + echo "ERROR: Please, run in CLI mode:\n"; |
| 8 | + echo "Example: php asana-json2csv.php path/to/filename.json\n\n"; |
| 9 | + exit(); |
| 10 | +} |
| 11 | + |
| 12 | +if (empty($argv[1])) { |
| 13 | + exit("ERROR: The json file name or URL is missed\n\n"); |
| 14 | +} |
| 15 | + |
| 16 | +$json_filename = $argv[1]; |
| 17 | + |
| 18 | +if (!file_exists($json_filename)) { |
| 19 | + exit("ERROR: File $json_filename not exists!\n\n"); |
| 20 | +} |
| 21 | + |
| 22 | +$json = file_get_contents($json_filename); |
| 23 | +$array = json_decode($json, true); |
| 24 | + |
| 25 | +$csv_filename = replace_extension($json_filename, "csv"); |
| 26 | + |
| 27 | +$f = fopen($csv_filename, 'w'); |
| 28 | + |
| 29 | +$header_line_array = ['Task ID', 'Created At', 'Completed At', 'Last Modified', 'Name', 'Assignee', 'Due Date', 'Tags', 'Notes', 'Projects', 'Parent Task']; |
| 30 | +fputcsv($f, $header_line_array); |
| 31 | + |
| 32 | +foreach ($array["data"] as $row) |
| 33 | +{ |
| 34 | + $csv_line = [ |
| 35 | + $row['id'], |
| 36 | + date_short_format($row['created_at']), |
| 37 | + date_short_format($row['completed_at']), |
| 38 | + date_short_format($row['modified_at']), |
| 39 | + $row['name'], |
| 40 | + $row['assignee']['name'], |
| 41 | + date_short_format($row['due_on']), |
| 42 | + tags_to_string($row['tags']), |
| 43 | + $row['notes'], |
| 44 | + $row['projects'][0]['name'], |
| 45 | + null, |
| 46 | + ]; |
| 47 | + |
| 48 | + echo "\n> ".$row['id'].' '.$row['name']; |
| 49 | + fputcsv($f, $csv_line); |
| 50 | +} |
| 51 | + |
| 52 | +fclose($f); |
| 53 | + |
| 54 | +exit("\n\nConvert Asana`s JSON to CSV completed!\n\n"); |
| 55 | + |
| 56 | +function tags_to_string($tags) |
| 57 | +{ |
| 58 | + if (count($tags)) { |
| 59 | + $new_tags = []; |
| 60 | + foreach ($tags as $tag) { |
| 61 | + $new_tags[] = $tag['name']; |
| 62 | + } |
| 63 | + return implode(",", $new_tags); |
| 64 | + } |
| 65 | + return null; |
| 66 | +} |
| 67 | + |
| 68 | +function date_short_format($date_string) |
| 69 | +{ |
| 70 | + if ($date_string === null) { |
| 71 | + return null; |
| 72 | + } |
| 73 | + |
| 74 | + $date = date_create($date_string); |
| 75 | + return date_format($date, 'Y-m-d'); |
| 76 | +} |
| 77 | + |
| 78 | +function replace_extension($filename, $new_extension) { |
| 79 | + return preg_replace('/\..+$/', '.' . $new_extension, $filename); |
| 80 | +} |
0 commit comments