Is this ok or should I just store it in an array form so I can just
directly access it without using json_decode?
In your case store it directly means store it serialized. Because $data
is an array and cannot be stored as is, but converted to a string.
Even if you access it directly like:
$data = get_transient('amazon_items');
print_r( $data[0] );
the get_transient
function unserialize the value behind the scenes (just like the set_transient
serialize behind the scenes), using the WP maybe_unserialze
function that use the serialize
php function.
So using json_encode
/json_decode
or using the standard php-serialize method there are some differences, but performance are almost the same. People who have done tests say json_encode
is a little bit faster.
The method you have to choose depends on what you have to do with data: if you plan to manipulate it with js (or even with other languages than php) the right choose is most probably json.
If you have to serialize php object, mantaining the original class you have to use php serialization:
$a = new MyClass;
$b = json_encode($a);
$c = json_decode($b);
$test = is_a($c, 'MyClass'); // false
$a = new MyClass;
$b = serialize($a);
$c = unserialize($b);
$test = is_a($c, 'MyClass'); // true
Is there a specific limit to how much data I can store using the
transients API?
Transient API use {$wpdb->prefix}_options
to save data. In this table the option_value
column where data are stored is a longtext
column that can theoretically contain 4Gb of data. Even if real space is less, 50Mb should not brings any problems (of course if your db space in server is big enough).
Side Notes
- When work with serialized data (json or php make no difference) you should be aware that running any type of SQL query that makes use of them is almost impossible. “Almost” is there for some
LIKE %..%
queries… - The process of serialization / deserialization is a bit expensive, especially for big data. So it can be (and actually is) useful, but try to keep this type of calls less frequent as possible, and if possible once a value is retrieved try to cache it in some way