9

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?

1

3 Answers 3

8
$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);
Sign up to request clarification or add additional context in comments.

2 Comments

dont know why I got null from your method
@swidmann likely spotted the issue, the single quotes need to be replaced with double quotes. updating my answer.
2

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 ) );

Comments

1

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

$string = str_replace(']', '', str_replace('[', '',$string));
$array = explode(',', $string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.