0

I'm currently trying to unserialize data given from a HTML data attribute. The value comes as a serialized string from my DB.

To get the value I'm doing a readout out of my DB. After that I'm replacing any " by ' to prevent problems with the opening and closing tag inside HTML:

<span data-value="<?= str_replace( '"', "'", $obj->value ) ?>"

Here is an example how it finally looks like:

<span data-value="a:2:{i:0;a:2:{s:5:'issue';s:4:'Test';s:10:'estimation';s:1:'5';}i:1;a:2:{s:5:'issue';s:4:'Impl';s:10:'estimation';s:1:'5';}}"></span>

My plan is now to receive the value in JS and transform it back to an array so that I can loop over it. I already tried JSON.parse() but that failed. Do you have any idea how to get this done?

Update:

Because some of you told me that my replace breaks my string, this here is the original one with an example:

jQuery( document ).ready( function ( $ ) {
  let attr = $("span").attr("data-test");
  
  console.log(JSON.parse(attr));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-test='a:2:{i:0;a:2:{s:5:"issue";s:4:"Test";s:10:"estimation";s:1:"5";}i:1;a:2:{s:5:"issue";s:4:"Impl";s:10:"estimation";s:1:"5";}}'></span>

9
  • Could please provide print($obj->value); here? Commented Dec 23, 2019 at 14:40
  • 1
    You may be better off unserializing it in PHP and then converting it to JSON before putting it in the data-value attribute. Commented Dec 23, 2019 at 14:40
  • Or just make a ajax request for the data on page load then handling the data in the java script Commented Dec 23, 2019 at 14:41
  • Your string replace breaks the unserialization Commented Dec 23, 2019 at 14:58
  • @NashPL In this case that wouldn't make sense. Commented Dec 23, 2019 at 14:59

1 Answer 1

1

You are trying to parse a serialised bit of data (not JSON) as JSON!

Instead just use JSON!

<?php

$x = 'a:2:{i:0;a:2:{s:5:"issue";s:4:"Test";s:10:"estimation";s:1:"5";}i:1;a:2:{s:5:"issue";s:4:"Impl";s:10:"estimation";s:1:"5";}}';
$array = unserialize($x);

header('Content-Type: application/json');
echo json_encode($array);

https://3v4l.org/Z3jJA

Now your thing will look like this:

<span data-value='[{"issue":"Test","estimation":"5"},{"issue":"Impl","estimation":"5"}]'></span>

Note that I used single quotes!

And your JS should work. :-)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.