Printing JSON object using PHP

Printing JSON object using PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Printing JSON Objects in PHP: Decoding the Output

When working with APIs or external data sources, you often need to fetch a JSON payload and render it back to the client. The goal is simple: take a JSON string, parse it into a usable structure, and output that same structure as valid JSON text. However, doing this correctly in PHP requires understanding how json_decode works internally and how json_encode reverses the process.

The source material presents a scenario where a developer successfully fetched data from an external URL and decoded it into a PHP array, but struggled to output it as JSON. The provided code snippet attempts to iterate over the decoded array and echo individual string values:

$jsonurl='http://website.com/international.json'; 
$json = file_get_contents($jsonurl,0,null,null);  
$json_output = json_decode($json);        
foreach ($json_output as $trend)  
{         
    echo "{$trend->text}\n";     
} 

There are two distinct issues here. First, the syntax {$trend->text} is invalid in a heredoc or double-quoted string context when trying to access properties; it should be {$trend['text']} or simply $trend['text']. Second, and more critically for the specific goal of "printing JSON," this approach outputs raw text strings separated by newlines. It does not produce a valid JSON block.

To output the data as JSON, you must use json_encode(). This function converts a PHP array or object back into a JSON string. When you combine json_decode and json_encode, you are essentially normalizing the data through PHP's internal representation. While this works for simple arrays of strings, it is often unnecessary overhead if you only need to pass the data through once.

Handling Associative Arrays vs. Indexed Arrays

The JSON payload in the example is an indexed array of objects:

[{"text": "Aachen, Germany - Aachen/Merzbruck (AAH)"}, {"text": "Aachen, Germany - Railway (ZIU)"}]

When json_decode processes this without the second parameter set to true, it returns an object with numeric keys. However, if you want to output the exact JSON string again, or if you need to modify the data slightly before sending it back, json_encode is the tool of choice.

Here is the corrected implementation that fetches the data and prints it as valid JSON:

$jsonurl = 'http://website.com/international.json';
$json_string = file_get_contents($jsonurl);

// Ensure we handle potential errors from file_get_contents gracefully
if ($json_string === false) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to fetch data']);
} else {
    // Echo the raw JSON if you just want to pass it through unchanged
    echo $json_string;
    
    // OR, if you need to process the data:
    // $decoded = json_decode($json_string); 
    // $output_json = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    // echo $output_json;
}

The var_dup() Error Explained

The error message reported in the source material, Fatal error: Call to undefined function var_dup(), is a classic symptom of a corrupted or incomplete file upload. In PHP, the file_get_contents function reads the entire content of a file from a specified path or URL into a string. If the remote server returns a partial response, or if the local file system contains a truncated version of the script, the parser might interpret parts of the code incorrectly.

Specifically, the error suggests that the PHP interpreter is seeing something it doesn't recognize as a valid function call within the context of the script execution flow. This often happens when:

  1. The remote URL returns malformed content that interferes with the parsing logic (though less likely to cause a specific function name error).
  2. There is a whitespace or encoding issue at the start of the file that causes the parser to misinterpret tokens.
  3. Most commonly, the script being executed is not the one intended, or there is a collision in namespace functions if a custom function named var_dup exists elsewhere but isn't loaded in this context.

However, looking closely at the provided code snippet, the line causing the issue is likely misinterpreted by a static analysis tool or an outdated PHP version due to how the string concatenation and property access are structured. The specific error var_dup() does not appear in standard PHP core functions. It is highly probable that the script file itself was uploaded incorrectly, resulting in a character encoding mismatch where $json_output or a variable name got mangled into something resembling var_dup.

Best Practices for JSON Handling

When building applications that consume and serve JSON, always consider the output format requirements. If the client expects a JSON array response, ensure your PHP script sets the appropriate headers:

header('Content-Type: application/json');

Using json_encode with flags like JSON_PRETTY_PRINT is useful for debugging in development environments but should be avoided in production endpoints to minimize payload size and parsing time on the client side. Additionally, always validate that file_get_contents returned a valid string before attempting to decode it. Attempting to decode an empty string or a boolean false will result in null values, leading to unexpected behavior downstream.

For developers using modern PHP frameworks like Laravel, handling JSON responses is streamlined via the response() helper method. If you need to return this data from a controller action, constructing the response object ensures headers are set correctly and the content type is automatically detected. For raw script execution, sticking to standard library functions remains robust and dependency-free.

Our network