How to convert XML to JSON in PHP

Cloudmersive
1 min readApr 15, 2020

Converting between file formats is nobody’s favorite topic, but we have to make the best of it. Need to switch your XML files into JSONs in a hurry? How about I show you how to do it in less than five minutes? That’s right, today’s your lucky day.

Installation is our first order of business. We shall handle it simply by running this command for composer:

composer require cloudmersive/cloudmersive_document_convert_api_client

And now:

<?phprequire_once(__DIR__ . '/vendor/autoload.php');// Configure API key authorization: Apikey$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Apikey', 'Bearer');$apiInstance = new Swagger\Client\Api\ConvertDataApi(// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.// This is optional, `GuzzleHttp\Client` will be used as default.new GuzzleHttp\Client(),$config);$input_file = "/path/to/file"; // \SplFileObject | Input file to perform the operation on.try {$result = $apiInstance->convertDataXmlToJson($input_file);print_r($result);} catch (Exception $e) {echo 'Exception when calling ConvertDataApi->convertDataXmlToJson: ', $e->getMessage(), PHP_EOL;}?>

This allows us to use convertDataXmlToJson, which will handle our work for us. Easy peasy. For the opposite form of this function, we also have convertDataJsonToXml.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.