Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a problem with parsing a HTML page. There is a variable in javascript that I need to get it and put it into json format.

<script>
  var variable1 = "foo";
  var variable2 = "boo";
  var multipleArray = [
            {"var1":"1",
             "var2": [{
                 "var21":"Extra Lge",
                 "var22":"45923090470",
                 "var23": {"key1":"value1",
                           "key2":"value"}
                 }],
                 ...etc...
             }]
</script>

Is there any easy way, how to get var multipleArray and all keys and values ? I used preg_match()

preg_match("'var multipleArray = [\{.*?\}]'", $source, $matches );

But it returns $matches as empty array().

What i am doing wrong? My experence with reg.ex. is on level 0 :(

I'll be glad for any help :) Thank you so much :)

share|improve this question
    
you should just pass the variable via ajax in pure json format and then capture it on php side and consume it. – DevZer0 Aug 20 '13 at 7:17
    
I cannot. Because i am parsing external web site. – wohral Aug 20 '13 at 7:25
    
you should probably use something like this developer.mozilla.org/en-US/docs/Rhino – DevZer0 Aug 20 '13 at 7:28

With th following pattern you should get the Array without the var multipleArray identifier.

preg_match('/\[(\{(.*)\})\]/', $source, $matches );

Now to get the key value pairs you have to parse it. Or if you want to have a quick, dirty and evil win you could do the following:

You use str_replace() to replace every ':' with '=>', '[{' with '[', '}]' with ']', '{' with '[', '}' with ']'.

With the result-string ($result) you do the following:

$result_array = null;
eval('$result_array = '.$result);

Now $result_array contains your Array.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.