將原始 JSON 資料轉換為精美的 HTML 頁面是現代 Web 應用程式的常見需求。 GroupDocs.Conversion Cloud SDK for PHP 使您能夠在 PHP 中以最少的程式碼實作 JSON 轉 HTML 的轉換教學。 在本指南中,您將看到完整的工作範例,學習如何使用 cURL 呼叫轉換 API,設定庫,並探討效能最佳實踐。
PHP 中的 JSON 轉 HTML 轉換教學 - 完整程式碼範例
以下範例示範如何讀取 JSON 檔案、產生 HTML 字串,並使用 GroupDocs.Conversion Cloud 函式庫來呈現結果。
<?php
require 'vendor/autoload.php';
use GroupDocs\Conversion\Api\ConversionApi;
use GroupDocs\Conversion\Model\Requests\ConvertDocumentRequest;
// Replace with your actual credentials
$clientId = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET';
// Initialize the API client
$apiInstance = new ConversionApi($clientId, $clientSecret);
// Path to the source JSON file
$jsonPath = 'data/input.json';
// Load JSON and convert to associative array
$jsonData = json_decode(file_get_contents($jsonPath), true);
if (json_last_error() !== JSON_ERROR_NONE) {
die('Invalid JSON: ' . json_last_error_msg());
}
// Build a simple HTML document from JSON data
$htmlContent = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Report</title></head><body>';
$htmlContent .= '<h1>Data Report</h1><ul>';
foreach ($jsonData as $key => $value) {
$htmlContent .= '<li><strong>' . htmlspecialchars($key) . ':</strong> ' .
htmlspecialchars($value) . '</li>';
}
$htmlContent .= '</ul></body></html>';
// Save the generated HTML to a temporary file
$tempHtmlPath = sys_get_temp_dir() . '/generated.html';
file_put_contents($tempHtmlPath, $htmlContent);
// Convert the HTML file to HTML output (no format change) to demonstrate SDK usage
$convertRequest = new ConvertDocumentRequest(
$tempHtmlPath,
'html',
'output.html' // output file path
);
try {
$apiInstance->convertDocument($convertRequest);
echo "Conversion successful. Output saved to output.html\n";
} catch (Exception $e) {
echo 'Conversion failed: ', $e->getMessage(), "\n";
}
// Clean up temporary file
unlink($tempHtmlPath);
?>
注意: 此代碼示例演示了核心功能。在將其用於您的項目之前,請確保更新文件路徑(
data/input.json、output.html等)以匹配實際文件位置,驗證所有必需的依賴項已正確安裝,並在開發環境中徹底測試。如果遇到任何問題,請參閱官方文檔或聯繫支持團隊尋求協助。
JSON 轉 HTML 轉換工具(使用 PHP 透過 REST API 並使用 cURL)
您可以直接呼叫 GroupDocs.Conversion Cloud REST API,而無需編寫 PHP 程式碼,即可實現相同的結果。以下步驟說明如何取得存取權杖、上傳 JSON 檔案、請求轉換以及下載產生的 HTML。
# 1. Get an access token
curl -X POST "https://api.groupdocs.cloud/v2.0/auth/token" \
-H "Content-Type: application/json" \
-d '{
"client_id": "YOUR_CLIENT_ID",
"client_secret": "YOUR_CLIENT_SECRET"
}'
# Response contains "access_token"
# 2. Upload the source JSON file
curl -X POST "https://api.groupdocs.cloud/v2.0/storage/file" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-F "file=@data/input.json"
# 3. Request conversion from JSON to HTML
curl -X POST "https://api.groupdocs.cloud/v2.0/conversion/json/html" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"file_path": "data/input.json",
"output_path": "output/result.html"
}'
# 4. Download the converted HTML file
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/output/result.html" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o result.html
For more details on request parameters, see the [official API documentation](https://docs.groupdocs.cloud/conversion/).
## 了解 PHP 程式碼中的 JSON 轉 HTML 轉換教學
Below is a step‑by‑step breakdown of the complete code example.
1. **Initialize the API client** – `new ConversionApi($clientId, $clientSecret)` creates a client that authenticates all subsequent calls.
2. **Read and decode JSON** – `json_decode(file_get_contents($jsonPath), true)` converts the file content into an associative array, handling errors with `json_last_error()`.
3. **Generate HTML** – A simple HTML template is built by looping through the array and escaping values with `htmlspecialchars()` to prevent XSS.
4. **Save temporary HTML** – `file_put_contents($tempHtmlPath, $htmlContent)` writes the HTML to a temporary location required by the SDK.
5. **Convert using the SDK** – `ConvertDocumentRequest` tells the API to process the temporary file and produce `output.html`. The conversion call is wrapped in a try‑catch block to capture any API errors.
6. **Cleanup** – `unlink($tempHtmlPath)` removes the temporary file to keep the server tidy.
### PHP 中 JSON 轉 HTML 轉換效能
The example streams the JSON file and builds the HTML string in memory, which is fast for typical payloads. For very large datasets, consider processing the JSON in chunks and writing directly to the output file to reduce memory usage.
### PHP 中 JSON 轉 HTML 批次轉換
Wrap the conversion logic inside a `foreach` loop and reuse the same `$apiInstance`. This minimizes authentication overhead and improves throughput when converting many JSON files.
### PHP 中 JSON 轉 HTML 轉換最佳實踐
* Validate JSON before processing.
* Escape all dynamic content with `htmlspecialchars()` to avoid XSS.
* Reuse the API client for multiple conversions.
* Use temporary files in a write‑protected directory.
## 在 PHP 中為 GroupDocs.Conversion 做好環境準備
1. **透過 Composer 安裝 SDK**
```bash
composer require groupdocs-conversion-cloud
從官方發佈頁面下載最新套件(可選): Download URL.
先決條件
- PHP 7.4 或更高版本。
- 具備有效 client ID 與 client secret 的 GroupDocs Cloud 帳戶。
- 需要能夠存取網際網路以呼叫 API。
設定憑證 - 將
YOUR_CLIENT_ID與YOUR_CLIENT_SECRET儲存在安全的設定檔或環境變數中。驗證安裝 - 執行
php -r "echo phpversion();"以確認 PHP 版本,並使用composer show groupdocs-conversion-cloud確認套件已安裝。
結論
在本
