XF 2.1 Converting array to json

mjda

Well-known member
Is there a function already built into XF that will do this? I'm trying to store an array in the database, but I'd like to convert it to json first.

I should mention that json_encode isn't working. It just returns NULL.
 
json_encode is correct. Are you 100% sure that your input data is valid UTF-8?

Which PHP version do you use? Unless it is really ancient (eg. < 5.5), json_encode should not return null on error.

Did you check json_last_error()?
 
Last edited:
json_encode is correct. Are you 100% sure that your input data is valid UTF-8?

Which PHP version do you use? Unless it is really ancient (eg. < 5.5), json_encode should not return null on error.

Did you check json_last_error()?

I'm using PHP 7.3. The data is pulled from the xf_thread table so I'd assume it's utf8. I'll try to figure out for sure tonight when I'm home.

I, honestly, didn't even know json_last_error existed so I'll check it tonight too.

Thanks for your help!
 
As you're using PHP 7.3, try:
PHP:
$json = json_encode($data, JSON_THROW_ON_ERROR);
That will throw a JsonException with details of the failure.

FWIW after PHP 5.5 there is also json_last_error_msg.
 
Last edited:
Well, I'm guessing now that my array must not be valid UTF-8?

I had the script echo the results of $json = json_encode($data) as well as json_last_error_msg() and that resulted in {} No error

Further testing is required...🤦‍♂️
 
Got it working now. Turns out you need to be working with an array rather than a PHP object. Doh! Thanks for the help, y'all.
 
Got it working now. Turns out you need to be working with an array rather than a PHP object. Doh! Thanks for the help, y'all.

What type of object was it? json_encode should work with objects, though in some circumstances I suppose you may get some unexpected results
 
What type of object was it? json_encode should work with objects, though in some circumstances I suppose you may get some unexpected results

It was fetched by using a simple finder \XF::finder('XF:Thread'). I'm not sure why it wouldn't encode it, but I ended up having to run a loop to convert everything within the object to an array, and then encode those.
 
It was fetched by using a simple finder \XF::finder('XF:Thread'). I'm not sure why it wouldn't encode it, but I ended up having to run a loop to convert everything within the object to an array, and then encode those.

You can't really serialize/jsonify entities, as their content is state and context dependent.
 
Back
Top Bottom