tags:

views:

60

answers:

4

I am accessing an external PHP server feed (not a real link):

$raw = file_get_contents('http://www.domain.com/getResults.php');

that returns data in the following context:

<pre>Array   
(   
    [RequestResult] => Array   
        (   
            [Response] => Success   
            [Value] => 100
            [Name] => Abracadabra
        )   
)   
</pre>

But I can't figure out how to handle this response... I would like to be able to grab the [Value] value and the [Name] value but my PHP skills are pretty weak... Additionally if there is a way to handle this with JavaScript (I'm a little better with JavaScript) then I could consider building my routine as a client side function...

Can anyone suggest a way to handle this feed response?

A: 

The script on the other side can return a JSON string of the array, and your client script can easily read it. See json_encode() and json_decode(). http://www.php.net/json-encode and http://www.php.net/json-decode

What you are doing on the "server" script is actually to var_dump the variable. var_dump is actually used more for debugging to see what a variable actually contains, not for data transfer.

On server script:

<?php

header("Content-Type: application/json");
$arr_to_output = array();

// ..  fill up array

echo json_encode($arr_to_output);

?>

The output of the script would be something like ['element1', 'element2'].

On client script:

<?php

$raw = file_get_contents('http://example.com/getData.php');

$arr = json_decode($raw, true); // true to make sure it returns array. else it will return object.

?>

Alternative

If the structure of the data is fixed this way, then you can try to do it dirty using regular expressions.

On client script:

<?php

$raw = file_get_contents('http://example.com/getData.php');

$arr = array('RequestResult'=>array());
preg_match('`\[Response\]\s\=\>\s([^\r\n]+)`is',$raw,$m);
$arr['RequestResult']['Response'] = $m[1];
preg_match('`\[Value\]\s\=\>\s([^\r\n]+)`is',$raw,$m);
$arr['RequestResult']['Value'] = $m[1];
preg_match('`\[Name\]\s\=\>\s([^\r\n]+)`is',$raw,$m);
$arr['RequestResult']['Name'] = $m[1];

// $arr is populated as the same structure as the one in the output.

?>
thephpdeveloper
I wish. I don't have any control of the source, only my consumption of their response...
Dscoduc
it is a pretty odd response
Ewan Todd
Yeah, it's probably written for a custom application... I am just trying to figure out how to 'extend' the use of the feed...
Dscoduc
try the alternative.
thephpdeveloper
i've tried the alternative myself. it works.
thephpdeveloper
How did you display the output? print $arr['RequestResult']['Name']
Dscoduc
yes. that's the way.
thephpdeveloper
hmm... you had luck but it doesn't seem to work for me... still working it...
Dscoduc
Thanks for your input... I was able to get the extraction using Ewan's info...
Dscoduc
A: 

does $raw[RequestResult][Value] not work? I think the data is just a nested hash table

toasteroven
just tried it and no, that doesn't work...
Dscoduc
Don't you mean `$raw['RequestResult']['Value']`
LiraNuna
Tried with/without quotes... no luck...
Dscoduc
+3  A: 

How about something like this

function responseToArray($raw)
{
   $result = array();

  foreach(explode("\n", $raw) as $line)
  {
    $line = trim($line);
    if(stripos($line, " => ") === false)
    {
      continue;
    }
    $toks = explode(' => ', $line);
    $k = str_replace(array('[',']'), "", $toks[0]);
    $result[$k] = $toks[1]; 


  }
  return $result;
}
Ewan Todd
This seems to display correctly when I do a foreach loop, but can't get the value when calling it directly:example: $data = responseToArray($raw);print $data['Name'];What did I miss?
Dscoduc
what do you get for `print_r($data)` ? (I'm flying blind here!)
Ewan Todd
This is what I see:Array ( [ [RequestResult]] => Array [ [Response]] => Success [ [Value]] => IP... ect...
Dscoduc
Did you get the version with the `str_replace` call to remove the square brackets? Also, you might need to trim `$k`.
Ewan Todd
Yeah, that was it... I missed your update... Works now, thank you... I will add the trim to $k for good measure...
Dscoduc
np ...................
Ewan Todd
Any chance you could convert this into a JavaScript function?
Dscoduc
Post that as a different question. You can use the snip if it helps!
Ewan Todd
A: 

Two possible solutions:

Solution #1 Change one line at the source:

It looks like getResults.php is doing a print_r. If that print_r could be changed to var_export you would get a PHP-parseable string to feed to eval:

$raw = file_get_contents('http://www.domain.com/getResults.php');
$a= eval($raw);
echo($raw['RequestResult']['Value']);

Be warned, eval'ing raw data from an external source (then echo()'ing it out) is not very secure

Solution #2 Parse with a regex:

<?php

$s= <<<EOS
<pre>Array   
(   
    [RequestResult] => Array   
        (   
            [Response] => Success   
            [Value] => 100
            [Name] => Abracadabra
        )   
)   
</pre>
EOS;

if (preg_match_all('/\[(\w+)\]\s+=>\s+(.+)/', $s, $m)) {
 print_r(array_combine($m[1], $m[2]));
}

?>

And now $a would contain: $a['Value']==100 and $a['Name']=='Abracadabra' etc.

pygorex1
solution one won't work at all. firstly there are html tags because there are `<pre>` tags.
thephpdeveloper
Yes, unfortunately I can't control the source...
Dscoduc
Ah, it's too bad nothing can be done at the source ... just one line to change!
pygorex1