如何在PHP 中使用cURL 檢索和解析jSON 資料
使用cURL 和PHP,您可以從URL 檢索JSON 資料並對其進行解碼以便在您的PHP 應用程式中使用。操作方法如下:
檢索jSON 資料
// Initiate cURL $ch = curl_init(); // Set cURL options curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response instead of printing it curl_setopt($ch, CURLOPT_URL, $url); // Set the URL to retrieve the jSON from // Execute the request and get the response $result = curl_exec($ch); // Close the cURL session curl_close($ch); // Parse the jSON response $data = json_decode($result, true); // Decode the response as an associative array
從jSON 物件擷取資料
從jSON 物件擷取資料
$title = $data['threads']['38752']['title']; $userId = $data['threads']['38752']['user_id']; $username = $data['threads']['38752']['username']; $postDate = $data['threads']['38752']['post_date']; $sticky = $data['threads']['38752']['sticky']; $discussionState = $data['threads']['38752']['discussion_state']; $discussionOpen = $data['threads']['38752']['discussion_open']; $message = $data['threads']['38752']['content']['content']['226167']['message'];
從jSON 物件擷取資料
,您可以將需要的值提取到PHP 變數中。操作方法如下:// Access the "count" element of the outer array $count = $array['count']; // Access the "thread_id" element of the first inner array (thread with id 13) $threadId = $array['threads'][13]['thread_id'];
解決陣列存取問題
要存取包含巢狀陣列的陣列中的元素,請使用下列語法:請注意,對於名為「[count]」的元素,您可以直接存取它,而無需將其括在括號中PHP,即 $count = $array["count"];.以上是如何使用 cURL 和 PHP 檢索和解析 JSON 資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!