how to convert object into string in php

how to convert object into string in php

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

Stefan Bogdanescu

Founder & Senior Architect

How to Convert an Object into a String in PHP

When integrating multiple web service APIs, you often encounter scenarios where the output of one call needs to be serialized as a string before becoming the input for another. This is a common pattern in data pipelines, yet it frequently triggers a "Catchable fatal error: Object of class stdClass could not be converted to string" if you attempt to pass the raw object directly into a function expecting a scalar value.

The error message indicates that PHP has retrieved an stdClass instance—essentially a generic associative array wrapper—and tried to cast it directly to a string without explicit instruction. The standard conversion functions like (string) casting or var_export() often fail here because they return verbose representations of the entire object structure rather than the specific primitive value you need.

Extracting Primitive Values from stdClass

The core issue in your scenario is that the API returns an entire object containing a property named document_number, but your second API expects just the raw string value '10ba60'. You cannot simply pass $responseObject to the second API; you must extract the specific field first.

If the response is stored in a variable like $data, and it contains a single property, the most direct approach is accessing that property explicitly:

// Assuming $response is the stdClass object returned by the first API
$documentNumber = $response->document_number;

// Now pass the scalar value to the second API
callSecondApi($documentNumber);

This method relies on knowing the exact property name defined in the first API's response schema. Since stdClass is dynamic, accessing a property by string key is also valid and often more robust if you are iterating over multiple fields:

$identifier = $response['document_number'];
callSecondApi($identifier);

Attempting to use print_r() or strval() on the whole object will output the entire object dump (e.g., stdClass Object (...)), which is useless for parsing downstream APIs. These functions are designed for debugging, not data serialization.

Serializing the Entire Object

If your requirement changes and you actually need to pass the entire object structure as a string to the second API, you must use a serialization function. PHP provides three primary methods for this: json_encode(), serialize(), and var_export().

JSON Encoding

For web services and HTTP APIs, json_encode() is the industry standard. It converts the stdClass into a compact JSON string. Most modern APIs expect JSON payloads or parameters.

$jsonPayload = json_encode($response);
// Result: {"document_number":"10ba60"}
callSecondApi($jsonPayload);

Using json_encode() is generally preferred over other methods because it produces clean, predictable output that adheres to standard data interchange formats. It handles null values and arrays gracefully, whereas serialize() includes PHP-specific metadata in the output string, which can cause issues if the receiving API parses the string as JSON.

Serialization vs. JSON

If you strictly need a binary representation rather than text (e.g., for internal caching or specific legacy systems), serialize() is an option:

$serialized = serialize($response);
// Result: s:13:"{\"document_number\":\"10ba60\"}"
callSecondApi($serialized);

However, be aware that the second API must specifically handle serialized PHP strings. If it attempts to json_decode() the input, it will fail because of the leading s: prefix. Always verify the expected input format of your downstream service before choosing a serialization method.

Handling Nested Structures and Arrays

Real-world API responses are rarely just flat objects with a single number. They often contain nested arrays or complex structures. If you need to convert such an object, json_encode() remains the safest bet because it recursively traverses the entire structure without altering the data types unexpectedly.

// Complex response example
$response = (object)['user' => ['id' => 123], 'status' => 'active'];

// Convert to JSON string safely
$jsonString = json_encode($response, JSON_UNESCAPED_UNICODE);

The JSON_UNESCAPED_UNICODE flag can be useful if you want to preserve UTF-8 characters without double-escaping them, ensuring the output is readable and compatible with most frontend or backend consumers.

Common Pitfalls in API Chaining

A frequent mistake when chaining APIs is assuming that a function returning an object automatically implies it can be passed as a string argument. Always inspect the return type of your first API call using var_dump() during development to confirm you are dealing with a scalar, an array, or an object.

If your second API expects a specific parameter name (e.g., ?document_number=), simply appending the serialized string might break query string parsing if the API logic expects a specific key-value pair rather than a raw blob. In such cases, you might need to parse the JSON first and reconstruct the request parameters manually:

$data = json_decode($jsonPayload);
callSecondApi('document_number' => $data->document_number);

By explicitly extracting the value before transmission, you avoid ambiguity and ensure that your data pipeline remains robust against edge cases where object structures vary slightly between API versions.

Our network