在PHP編程中,將數據快速轉換為JSON格式
以JSON格式存儲的數據通常更容易處理。然而,我們并不總能選擇數據到達時的格式。
值得慶幸的是,我們可以通過調用一些免費的API和配套的PHP代碼示例,將幾種常見的數據格式轉換為JSON格式。在這里,我們可以快速且輕松地將CSV、XLSX(Excel)和XML轉換為JSON格式,而不會遇到任何麻煩。
可以使用下面提供的代碼調用這三個API,并且只需運行一個命令即可為所有三個API安裝客戶端SDK。此外,我們可以使用一個Cloudmersive API密鑰來授權我們的數據轉換請求(這將支持我們以零投入的方式進行多達800次API調用)。
安裝PHP客戶端
要使用Composer安裝PHP客戶端,可以在命令行中執行以下命令。
composer require cloudmersive/cloudmersive_document_convert_api_client
完成安裝后,就可以復制所需的轉換代碼了。
1. 將CSV數據轉換為JSON
可以使用以下代碼將CSV數據轉換為JSON(請注意,可以設置$column_names_from_first_row參數來自定義列的標簽)。
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// 配置API密鑰授權: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 | 要執行操作的輸入文件。
$column_names_from_first_row = true; // bool | 可選;如果為 true,第一行將用作列的標簽;如果為 false,列將命名為 Column0、Column1 等。默認值為 true。如果不使用列標題或具有不規則的列結構,請設置為 false。
try {
$result = $apiInstance->convertDataCsvToJson($input_file, $column_names_from_first_row);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertDataApi->convertDataCsvToJson: ', $e->getMessage(), PHP_EOL;
}
?>
2. 將XLSX(Excel)轉換為JSON
可以使用下面的代碼將XLSX(Excel)轉換為JSON。
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// 配置API密鑰授權: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 | 要執行操作的輸入文件。
try {
$result = $apiInstance->convertDataXlsxToJson($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertDataApi->convertDataXlsxToJson: ', $e->getMessage(), PHP_EOL;
}
?>
3. 將XML轉換為JSON
最后,可以使用以下代碼將XML轉換為JSON。
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// 配置API密鑰授權: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 | 要執行操作的輸入文件。
try {
$result = $apiInstance->convertDataXmlToJson($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertDataApi->convertDataXmlToJson: ', $e->getMessage(), PHP_EOL;
}
?>
結語
這就是我們所需的所有代碼!現在,我們可以輕松地在PHP應用程序中將幾種常見的數據格式轉換為JSON格式。