Laravel中Storage::getData()返回含外层字符串的对象无法访问属性求助
Hey Shabin, I’ve run into similar weird output quirks before, so let’s break this down and get it sorted step by step.
What’s Actually Happening?
The output you’re seeing looks like the result of a var_dump() or print_r() call wrapped in a string—not the raw object itself. That’s why trying to access $content->GetNewTransactionsResult throws an error: you’re trying to treat a plain string like an object.
Quick Fix: Convert the String-Wrapped Object to a Real PHP Object
We’ll extract the object content from the string and turn it into a usable stdClass object. Here’s how:
Strip the outer string wrapper
First, remove thestring(4794) "..."part to isolate thestdClass Object (...)content:// Remove the leading "string(xxx) " and trailing quote $cleanedContent = preg_replace('/^string\(\d+\) "/', '', $content); $cleanedContent = rtrim($cleanedContent, '"');Convert the print_r-style string to a real object
The remaining string usesprint_rformatting, which we can convert to an array first, then cast to an object:// Rewrite the print_r object syntax to valid array syntax $arraySyntax = preg_replace('/stdClass Object \((.*)\)/s', '$1', $cleanedContent); $arraySyntax = preg_replace('/\[([^\]]+)\] =>/', '$1 =>', $arraySyntax); $arraySyntax = str_replace(["\n", " "], '', $arraySyntax); // Remove newlines and indentation $arraySyntax = "array($arraySyntax)"; // Evaluate the array string and cast to an object $realObject = (object) eval("return $arraySyntax;");Now you can safely access the properties as intended:
echo $realObject->GetNewTransactionsResult; // Outputs 0 echo $realObject->xmlTransactions; // Outputs 0⚠️ Heads up:
eval()carries risk if working with untrusted data, but since this is your stored content, it’s safe here.
Better Long-Term Fix: Fix How You Store the Data
The root issue is that you’re storing debug output instead of the raw object. Let’s fix this to avoid the problem entirely:
Option 1: Use Serialization
Store the serialized object instead of a debug string:
// When saving the object $object = (object) [ 'GetNewTransactionsResult' => 0, 'xmlTransactions' => 0 ]; Storage::put('your-file.txt', serialize($object)); // When retrieving it later $content = Storage::get('your-file.txt'); $realObject = unserialize($content);
Option 2: Use JSON (Human-Readable)
JSON is a great choice if you want the stored data to be readable:
// When saving the object $object = (object) [ 'GetNewTransactionsResult' => 0, 'xmlTransactions' => 0 ]; Storage::put('your-file.txt', json_encode($object)); // When retrieving it later $content = Storage::get('your-file.txt'); $realObject = json_decode($content);
Either method will give you a direct, usable object without needing to parse messy strings.
内容的提问来源于stack exchange,提问作者user3727110

