Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a PHP script with curl's an external site which returns a javascript array that looks like this:

array[0]='some stuff'

array[1]='some more stuff'

I would like to take this and convert it into a PHP array so I can reference it later down in the script for echoing. Is this the way to go about doing it? Is there a better way?

Thanks!

share|improve this question
Can't you just add a $ to array, then a ; at the end of each line? – bozdoz Mar 20 '12 at 19:57
This would make it into an array that PHP would accept, but at that stage it's still sitting in the variable that curl dumped it into. How can I convert that into a PHP array I can access? – user1247483 Mar 20 '12 at 20:06

2 Answers

up vote 0 down vote accepted

If it's a String array, you can use regular expressions:

with this:

preg_match( "\[(\d+)\]='(.*)'" , $curlString , $matches )

you can obtain the index, and the value:

i.e, response of curl:

 array[0] = 'abc';
 array[1] = 'xyz';

before preg_match, the value of $matches was:

 $matches[0] == '0';
 $matches[1] == 'abc';
 $matches[1] == '1';
 $matches[2] == 'xyz';

And with something like this:

for($i = 0; $i < len($matches);$i +=2)
     $finalArray[$matches[i]] = $matches[i+1];

the $finalArray has the same values of "array"

This code can contain errors.

share|improve this answer
Thank you very much. – user1247483 Mar 20 '12 at 20:52
It works? Excelent! – Nullpo Mar 21 '12 at 13:10

if your javascript page return JSON (Javascripit object notation) in http request, you can tranform it in php array with json_decode() php function.

share|improve this answer
Unfortunately it returns only what I posted above. A javascript format array in plain text. – user1247483 Mar 20 '12 at 20:10

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.