> For the complete documentation index, see [llms.txt](https://doc.wearepatchworks.com/product-documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.wearepatchworks.com/product-documentation/~/changes/J8IbZkP6ASUZu2oBhGi2/developer-hub/custom-scripting/custom-script-examples.md).

# 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.

## PHP

<details>

<summary><img src="https://2440044887-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FLYNcUBVQwSkOMG6KjZfz%2Fuploads%2FoTQs7eEfsfqZUPfRoiT7%2Ficon_code.svg?alt=media&amp;token=b4a6f8e5-8ebf-4ef8-ab24-a130d29b50c5" alt="" data-size="line"> Converting JSON to CSV</summary>

```php
<?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'];
}
```

</details>

## C\#

This script takes an XML input string, loads it into an `XmlDocument`, and then converts that XML to a JSON string using the `Newtonsoft.Json` library.

<details>

<summary><img src="https://2440044887-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FLYNcUBVQwSkOMG6KjZfz%2Fuploads%2FoTQs7eEfsfqZUPfRoiT7%2Ficon_code.svg?alt=media&amp;token=b4a6f8e5-8ebf-4ef8-ab24-a130d29b50c5" alt="" data-size="line"> Converting XML to JSON</summary>

```csharp
using System;
using System.Xml;
using Newtonsoft.Json;
public class FunctionHandler
{
    public string Handle(string input)
    {
        var xmlDoc = new XmlDocument();
        
        // Set up XML namespace manager
        var namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
        namespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        namespaceManager.AddNamespace("", "http://api.jdplc.com/schemas/mc/pim/feproducts");
        
        // Load the XML string into XmlDocument
        xmlDoc.LoadXml(input);

        // Convert the XML to JSON
        string jsonText = JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.Indented, true);

        return jsonText;
    }
}
```

</details>
