How to Convert CSV to XML in PHP
Converting between data formats in any programming language can be a pain without the right tools at your disposal. Thankfully, the free-to-use API below makes converting between two especially common formats — CSV and XML — incredibly easy. Just use the ready-to-run PHP code examples provided in this article to structure your API call, and you’ll quickly implement a scalable file conversion feature into your application with zero hassle.
To install the PHP SDK, run this command:
composer require cloudmersive/cloudmersive_document_convert_api_client
After that, provide your API key (you can get one for free here) and call the function:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\ConvertDataApi(
new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/inputfile"; // \SplFileObject | Input file to perform the operation on.
$column_names_from_first_row = true; // bool | Optional; If true, the first row will be used as the labels for the columns; if false, columns will be named Column0, Column1, etc. Default is true. Set to false if you are not using column headings, or have an irregular column structure.
try {
$result = $apiInstance->convertDataCsvToXml($input_file, $column_names_from_first_row);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertDataApi->convertDataCsvToXml: ', $e->getMessage(), PHP_EOL;
}
?>
Just like that, you’re all set — no more code required!