- ⚠️ A common PHP error happens when you pass a stdClass object directly to cURL without encoding it.
- 💻 PHP’s cURL needs data as a string, usually JSON, not objects.
- ✅ Making
stdClassobjects into JSON fixes most cURL type errors in API calls. - 🗺️ Google Cloud's computeRoutes API needs specific, nested JSON structures.
- 🧰 Developers can switch between
stdClassand associative arrays withjson_encode/json_decode.
Curl Error: Object of stdClass Not a String?
When you make API calls in PHP with Curl, especially to complex services like Google Cloud’s computeRoutes, errors can stop your work. A confusing message you might see is: "Object of class stdClass could not be converted to string." This post explains what this means, why it happens, and how to fix it. You will find practical, tested ways to solve this, whether you are starting new code or fixing an existing one.
What the Error Message Means
In PHP, the message "Object of class stdClass could not be converted to string" comes up when a script tries to use an object like a string. Objects are complex data. They cannot turn into a string on their own. You need to tell PHP how to do it. Here is a common example that causes this error:
$object = new stdClass();
echo $object; // Fatal error: Object of class stdClass could not be converted to string
PHP tries to use the __toString() method, but stdClass does not have this method. Because of this, PHP does not know how to read the object as a simple value for display. So, it stops running and gives a fatal error.
This simple sign causes problems when you use cURL. Incorrect data formatting leads to unreadable data and API failures.
Why This Happens in Curl Requests
PHP cURL works with strings. The CURLOPT_POSTFIELDS option needs one of two data types:
- A URL-encoded query string, such as
key1=value1&key2=value2. - A correct JSON string for APIs that read raw body data.
If you send objects directly, like stdClass, you do not use either of these formats. And then you get this error:
$data = new stdClass();
$data->origin = "Seattle, WA";
$data->destination = "Portland, OR";
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // ❌ Causes fatal error
You are telling cURL to send an object that it cannot read, instead of a format it can understand. PHP does not know how to turn the object into a string for the request body.
This problem often shows up with services like Google Maps Platform’s computeRoutes. These services need request data that has many objects inside other objects.
About stdClass in PHP
It is basic to understand stdClass when you decode JSON in PHP.
stdClass is PHP’s simple empty class. You usually get it when you use json_decode() on a JSON string:
$json = '{"key": "value"}';
$obj = json_decode($json); // Gives a stdClass object
echo $obj->key; // Shows: value
This class lets you read JSON and get to data using object syntax (->). But it has limits when you need to work with strings or change data. This happens when you must put together a correct HTTP request body.
Unlike arrays, stdClass objects:
- Do not let you check if a key exists with
isset($obj['key'])(you need$obj->key). - Cannot be used in loops like
foreach ($obj as $key => $value)unless you change them to another type or decode them. - Cannot be shown directly as a string without
json_encode.
When you make data structures for API calls or get replies from APIs, you will often switch between stdClass and arrays.
Common Mistake: Not Understanding How Curl Payloads Work
API calls with PHP cURL can fail without you knowing if you do not understand how to format the data. Let’s look at a wrong way to do it:
$data = new stdClass();
$data->mode = "DRIVE";
$data->units = "METRIC";
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // ❌ Wrong format
What is going on here? You are trying to put an object right into an HTTP request body. PHP cURL is not made to turn objects into strings for sending. So, it tries (and fails) to change it to a string. This causes a type error. This stops the request process completely.
With strict APIs like Google’s computeRoute, even small formatting mistakes can cause HTTP 400 or 500 errors. Always use JSON strings that are already formatted. This helps avoid errors that stop things from working together. And always check what the API needs.
How to Fix the Error: Make Your Payload JSON Correctly
To send data safely with cURL, you must change your PHP objects (like stdClass) into JSON strings that are correctly encoded.
The right way to do it:
$data = new stdClass();
$data->mode = "DRIVE";
$data->units = "METRIC";
$payload = json_encode($data); // ✅ Correctly makes it a JSON string
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
This small change makes sure cURL sends good JSON. It does not send raw PHP object data that it cannot process.
Dieken (2023) says that not encoding the data correctly, especially forgetting json_encode() for the payload, is one of the main reasons HTTP requests fail with cURL in PHP.
Handling API Responses
After you send a cURL request, you will usually want to do something with the reply. Most APIs send back JSON. This means json_decode() is the safest way to get this data into PHP.
Basic use:
$response = curl_exec($ch);
$data = json_decode($response); // Makes a stdClass by default
echo $data->route->name;
You might like to work with arrays. This is often easier for many keys, running loops, or using PHP’s array functions. If so, decode the data into an associative array:
$data = json_decode($response, true); // Now gives an associative array
echo $data['route']['name'];
This is very helpful when the API’s reply has keys that change or has nesting that you cannot guess.
Using Arrays or stdClass
Both ways—associative arrays and stdClass—work. But you need to know when to use each for cleaner, stronger code.
When to Use stdClass
- The object structure matches the JSON body well.
- You like object syntax (
$obj->key). - It is simpler for flat or known structures.
When to Use Associative Arrays
- You need to find and change keys.
- It works better with functions like
array_map(),foreach,array_search(). - It is easier to read when keys can change or are nested.
How to Change Between Formats
To change a stdClass object to an associative array:
$array = json_decode(json_encode($object), true);
To make JSON into stdClass:
$obj = json_decode($json, false); // false is the default setting
This lets you change how the data looks depending on what you need, without rewriting much code.
How to Debug: Check Your Data Before Sending
Before you make a cURL call, especially with deeply nested route data or third-party APIs, always check the data you are sending.
Use:
var_dump($payload);
Or:
echo json_encode($data, JSON_PRETTY_PRINT);
To debug the real cURL reply:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$error = curl_error($ch);
echo "HTTP Code: " . $info['http_code'] . "\n";
echo "Request Info:\n";
print_r($info);
echo "Error Message: " . $error;
This detailed information helps you find format errors, problems with the connection, and even unusual response times.
Working with Google’s computeRoutes API
Developers often run into cURL serialization errors with Google’s computeRoutes API from Google Maps Platform. This is one of the most common places it happens.
This API is strict. It needs a JSON payload structure with many nested parts, including types like latLng, location, and travelMode.
Correct payload:
{
"origin": {
"location": {
"latLng": {
"latitude": 47.60357,
"longitude": -122.32945
}
}
},
"destination": {
"location": {
"latLng": {
"latitude": 45.50511,
"longitude": -122.67552
}
}
},
"travelMode": "DRIVE"
}
In PHP, make it with either a nested array or an object:
$request = [
"origin" => [
"location" => [
"latLng" => [
"latitude" => 47.60357,
"longitude" => -122.32945
]
]
],
"destination" => [
"location" => [
"latLng" => [
"latitude" => 45.50511,
"longitude" => -122.67552
]
]
],
"travelMode" => "DRIVE"
];
$payload = json_encode($request);
Make sure the header setup is correct:
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer YOUR_ACCESS_TOKEN'
]);
If you do not send the payload or headers in the right way, you will almost certainly get HTTP errors.
Important Curl and HTTP Headers
When you work with JSON APIs, headers show how to talk to them. If you leave out headers or set them wrong, your request can fail without a warning.
Headers needed with computeRoutes:
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer {API_ACCESS_TOKEN}'
]);
Other common header errors:
- Sending
Content-Type: text/plainby default (this stops JSON from being read). - Forgetting the Authorization header (you will get 401 errors).
- Using a query string for the API key when a bearer token is needed.
Headers should always match what the service's instructions say.
Things to Avoid and Common Developer Mistakes
Do not make these mistakes when you work with cURL and stdClass in PHP:
- ❌ Showing objects directly (
echo $obj). - ❌ Sending raw
stdClassinCURLOPT_POSTFIELDS. - ❌ Forgetting
json_encode()before POST. - ❌ Not checking header needs, like
Content-Type: application/json. - ❌ Not checking the API data structure.
Even skilled developers make these errors when they build new connections fast. Just a moment to check object changes and data formats can save many hours of fixing problems.
Stop the Error, Fix It, and Keep Going
The PHP cURL error—“Object of class stdClass could not be converted to string”—is more than just annoying. It shows you are handling data wrong or do not understand the format for HTTP requests.
To get rid of this problem:
- ✅ Always
json_encode()PHP objects before sending them with cURL. - ✅ Use
json_decode($response, true)when reply data needs array changes. - ✅ Make data structure match API instructions (especially nesting and field names).
- ✅ Set correct headers for content type and authorization.
- ✅ Check payloads and replies with
var_dump()orcurl_getinfo().
Learning these practices helps with smoother API talks, clearer error checks, and ready-to-use PHP connections.
Next time you see a stdClass conversion PHP error, know you can fix it.
Citations
PHP Manual. (2024). stdClass. Retrieved from https://www.php.net/manual/en/class.stdclass.php
Google Cloud. (2024). Routes API documentation. Retrieved from https://cloud.google.com/maps-platform/routes
Dieken, J. (2023). Techniques for sending JSON with PHP cURL. Developer’s Digest.