以JSON格式存儲的數(shù)據(jù)通常更容易處理。然而,我們并不總能選擇數(shù)據(jù)到達時的格式。
值得慶幸的是,我們可以通過調(diào)用一些免費的API和配套的PHP代碼示例,將幾種常見的數(shù)據(jù)格式轉(zhuǎn)換為JSON格式。在這里,我們可以快速且輕松地將CSV、XLSX(Excel)和XML轉(zhuǎn)換為JSON格式,而不會遇到任何麻煩。
可以使用下面提供的代碼調(diào)用這三個API,并且只需運行一個命令即可為所有三個API安裝客戶端SDK。此外,我們可以使用一個Cloudmersive API密鑰來授權(quán)我們的數(shù)據(jù)轉(zhuǎn)換請求(這將支持我們以零投入的方式進行多達800次API調(diào)用)。
要使用Composer安裝PHP客戶端,可以在命令行中執(zhí)行以下命令。
composer require cloudmersive/cloudmersive_document_convert_api_client
完成安裝后,就可以復(fù)制所需的轉(zhuǎn)換代碼了。
可以使用以下代碼將CSV數(shù)據(jù)轉(zhuǎn)換為JSON(請注意,可以設(shè)置$column_names_from_first_row參數(shù)來自定義列的標簽)。
<?phprequire_once(__DIR__ . '/vendor/autoload.php');// 配置API密鑰授權(quán):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 | 要執(zhí)行操作的輸入文件。$column_names_from_first_row = true; // bool | 可選;如果為 true,第一行將用作列的標簽;如果為 false,列將命名為 Column0、Column1 等。默認值為 true。如果不使用列標題或具有不規(guī)則的列結(jié)構(gòu),請設(shè)置為 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;}?>
可以使用下面的代碼將XLSX(Excel)轉(zhuǎn)換為JSON。
<?phprequire_once(__DIR__ . '/vendor/autoload.php');// 配置API密鑰授權(quán):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 | 要執(zhí)行操作的輸入文件。try { $result = $apiInstance->convertDataXlsxToJson($input_file); print_r($result);} catch (Exception $e) { echo 'Exception when calling ConvertDataApi->convertDataXlsxToJson: ', $e->getMessage(), PHP_EOL;}?>
最后,可以使用以下代碼將XML轉(zhuǎn)換為JSON。
<?phprequire_once(__DIR__ . '/vendor/autoload.php');// 配置API密鑰授權(quán):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 | 要執(zhí)行操作的輸入文件。try { $result = $apiInstance->convertDataXmlToJson($input_file); print_r($result);} catch (Exception $e) { echo 'Exception when calling ConvertDataApi->convertDataXmlToJson: ', $e->getMessage(), PHP_EOL;}?>
這就是我們所需的所有代碼!現(xiàn)在,我們可以輕松地在PHP應(yīng)用程序中將幾種常見的數(shù)據(jù)格式轉(zhuǎn)換為JSON格式。
本文鏈接:http://www.tebozhan.com/showinfo-26-112705-0.html在PHP編程中,將數(shù)據(jù)快速轉(zhuǎn)換為JSON格式
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 面試官:一個子任務(wù)要依賴兩個父任務(wù)完成才能執(zhí)行,該怎么設(shè)計?
下一篇: 一個簡單的車輛目標檢測和跟蹤示例