Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert javascript string to php array

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?

like image 389
PappApp Avatar asked Nov 23 '15 09:11

PappApp


3 Answers

$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);
like image 56
Calimero Avatar answered Oct 19 '22 19:10

Calimero


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 ) );
like image 37
swidmann Avatar answered Oct 19 '22 20:10

swidmann


You can try replacing the [ ] with '' and then breaking the string.

$string = str_replace(']', '', str_replace('[', '',$string));
$array = explode(',', $string);
like image 1
Basit Avatar answered Oct 19 '22 19:10

Basit