I'm scraping a website using php to get some data. The data I get is a valid javascript array.
"['v42, 2015', 23428, 30243, 76993]
,
['v43, 2015', 24060, 30401, 73412]
,
['v44, 2015', 22855, 29720, 71573]
,
['v45, 2015', 24455, 30757, 78991]
,
['v46, 2015', 24275, 30398, 84424]"
I now have this string in php, but how can I convert it to a php array?
$string = "['v42, 2015', 23428, 30243, 76993]
,
['v43, 2015', 24060, 30401, 73412]
,
['v44, 2015', 22855, 29720, 71573]
,
['v45, 2015', 24455, 30757, 78991]
,
['v46, 2015', 24275, 30398, 84424]";
It is a valid js array if you add the proper start & end square brackets delimiter. Furthermore, to comply with the php json parser requirements, the string delimiters must be double-quoted instead of single-quoted, so a quick replacement must be done.
You then can decode it like so :
$ary = json_decode('['.str_replace("'",'"',$string).']', true);
The single quotes may be valid in JS, but JSON sometimes have a problem with it. You can try it here: JSONLint
To get a valid JSON, just replace the single quotes '
with double quotes "
, to get an array with arrays you have to surround your string with brackets []
.
Try this example code:
$string = "['v42, 2015', 23428, 30243, 76993]
,
['v43, 2015', 24060, 30401, 73412]
,
['v44, 2015', 22855, 29720, 71573]
,
['v45, 2015', 24455, 30757, 78991]
,
['v46, 2015', 24275, 30398, 84424]";
$string = str_replace( "'" , '"', $string );
$string = '['.$string.']';
echo "<pre>";
var_dump( json_decode( $string ) );
You can try replacing the [ ]
with ''
and then breaking the string.
$string = str_replace(']', '', str_replace('[', '',$string));
$array = explode(',', $string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With