Product documentation
Patchworks
Search
K
Comment on page

Custom script examples

Introduction

This page includes scripts that may be useful either in and of themselves, or as a start point for your own scripting work.
Converting JSON to CSV
<?php
function handle($data) {
// Decode the JSON string into an array
$dataArray = json_decode($data['payload'], true);
if ($dataArray === null) {
// JSON decoding failed
return 'Failed to decode JSON.';
}
// Create an empty array to store the CSV rows
$csvRows = [];
// Add the CSV headers
if (!empty($dataArray)) {
$headers = array_keys($dataArray[0]);
$csvRows[] = $headers;
}
// Add the CSV rows
foreach ($dataArray as $row) {
$csvRows[] = array_values($row);
}
// Generate the CSV string
$csvString = '';
foreach ($csvRows as $row) {
$csvString .= implode(',', $row) . "\n";
}
// Return the CSV string or error message
return ['payload' => !empty($csvString) ? $csvString : 'Failed to convert JSON to CSV'];
}