0

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?

4 Answers 4

3

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

7 Comments

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?
what do you get for print_r($data) ? (I'm flying blind here!)
This is what I see: Array ( [ [RequestResult]] => Array [ [Response]] => Success [ [Value]] => IP... ect...
Did you get the version with the str_replace call to remove the square brackets? Also, you might need to trim $k.
Yeah, that was it... I missed your update... Works now, thank you... I will add the trim to $k for good measure...
|
0

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

1 Comment

Don't you mean $raw['RequestResult']['Value']
0

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.

?>

3 Comments

I wish. I don't have any control of the source, only my consumption of their response...
Yeah, it's probably written for a custom application... I am just trying to figure out how to 'extend' the use of the feed...
How did you display the output? print $arr['RequestResult']['Name']
0

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.

2 Comments

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

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.