How to parse JSON and access results

How to parse JSON and access results

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Parsing JSON Responses and Integrating Data into Databases

When you execute a cURL request that returns data formatted as JSON, simply printing the raw string via print_r($result) is rarely sufficient for application logic. To insert this information into a database, you must transform the string output from curl_exec into an associative array or object. This process involves decoding the string and then mapping specific fields to your persistence layer.

Decoding the Response String

The variable $result currently holds a string representation of the JSON payload. You need to convert this into a PHP array using the built-in json_decode function. By default, json_decode returns an object. While objects work well for accessing properties via dot notation (e.g., $data->MessageID), arrays are generally safer when inserting data into databases because they allow you to reference values by key name without worrying about class instantiation quirks.

To achieve this, pass the second argument of json_decode as true. This forces the function to return an associative array:

$response = json_decode($result, true);

If $response remains null after execution, it indicates that the JSON parsing failed. This often happens if the server returns a malformed string or if you are dealing with HTML error pages instead of valid JSON. Always validate the decoded result before proceeding to database operations:

if ($response === null) {
    // Handle parsing error, e.g., log the raw $result for debugging
    error_log("Failed to parse JSON response");
} else {
    // Proceed with safe access
}

Mapping Fields to Database Insertions

Once you have an associative array, accessing specific keys is straightforward. Looking at your specific output, the MessageID field contains a UUID that should be stored in your database. However, notice the presence of the SentDateTime field: /Date(-62135578800000-0500)/. This is not a standard JavaScript date string; it uses the .NET JSON serialization format common in older Web Services.

If you attempt to insert this raw string directly into a DATETIME column in MySQL or PostgreSQL, you will encounter a conversion error. You must parse this string into a native PHP DateTime object before inserting it. The easiest way is to strip the /Date(...)/ wrapper and replace the timezone offset with 'Z' (UTC) or simply let PHP handle the ISO 8601 format if the server changes its output:

$rawDate = $response->SentDateTime; // Accessing as object for clarity first
// Or using array access: $rawDate = $response['SentDateTime'];

// Clean up the .NET date format
$dateString = str_replace(['/Date(', ')-0500)', ')'], '', $rawDate);

$datetimeObj = new DateTime($dateString);

For the boolean fields like Cancelled, Queued, and Sent, you can insert them directly as integers (1/0) or booleans depending on your database schema. Most modern SQL drivers handle PHP booleans automatically, converting them to 0 or 1 in the backend.

Handling Potential Pitfalls

A critical aspect of this workflow is error handling. The source code snippet initializes cURL with CURLOPT_HTTPGET set to true, but the URL string includes parameters like PhoneNumber and Message. If the server expects a POST request for these parameters despite the GET flag, the response might return an HTML error page (e.g., "405 Method Not Allowed") instead of JSON.

If cURL follows this path, json_decode will fail because the input is no longer valid JSON text. To mitigate this, check the HTTP status code returned by cURL using curl_getinfo($cURL, CURLINFO_HTTP_CODE) before attempting to decode. If the status code indicates an error (anything other than 200), skip the decoding step and handle the HTTP error appropriately.

Furthermore, ensure that your database connection is properly configured to handle UUIDs for the MessageID field and UTC timestamps for dates. Mismatched data types here are a common source of silent data corruption or application crashes during batch processing.

Our network