tags:

views:

392

answers:

2

Hello

I want to make use of an API but it print alot of info and i don't know how i can get a few key values of the array.

<?php
$query = "SELECT * FROM kvk WHERE adres='Wit-geellaan 158'";
$host  = "http://api.openkvk.nl/php/";
$url   = $host ."/". rawurlencode($query);

$curl = curl_init();
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0); 

curl_exec($curl);

curl_close($curl);
?>

Is my php script and it shows

array(array("RESULT"=>array("TYPES"=>array("int","bigint","varchar","varchar","varchar","varchar","varchar","int","int","smallint","smallint","int"),"HEADER"=>array("id","kvk","bedrijfsnaam","adres","postcode","plaats","type","kvks","sub","bedrijfsnaam_size","adres_size","verhuisd"),"ROWS"=>array(array("1303095","271242250000","Schoonmaakbedrijf Regio","Wit-geellaan 158","2718CK","Zoetermeer","Hoofdvestiging","27124225","0","23","16","0")))))

Thanks in advance

Greetings, Vierri

A: 

To get all keys and values:

$server_output = curl_exec($curl);
var_dump($server_output);

To just get a list of keys:

$server_output = curl_exec($curl);
ksort($server_output);
foreach ( $server_output AS $key => $val ) {
  echo "$key\n";
}
Paul
The response is a string not an array. `ksort` and `foreach` expect arrays.
Yacoby
+2  A: 
//Use the cURL setting to put the result into a variable rather than printing it    
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 

//store the result rather than print (as we set CURLOPT_RETURNTRANSFER)
$result = curl_exec($curl);
if ( $result === false ){
    //something went wrong, handle the error
}

//evaluate the array result and store it. (Please don't use this line in production code)
//as the $result string is from a untrusted source
eval('$array = '.$result.';');

//then you can, for example, get a list of the types
$types = $array[0]['RESULT']['TYPES'];


//or some keys
$keys = array_keys($array[0]['RESULT']);

The above code is dangerous and probably shouldn't be used as it is. They could put anything nasty in the response and you would evaluate it (the eval line) which could do bad things to your server. I would check if they have a better API that doesn't send responses in that format. (json or XML would be better)

If not you may want to considerer manually parsing the response array rather than using eval

Yacoby
Hello thnx for your response,Parse error: syntax error, unexpected $end in /var/www/clients/client5/web6/web/test.php(20) : eval()'d code on line 1Warning: array_keys() [function.array-keys]: The first argument should be an array in /var/www/clients/client5/web6/web/test.php on line 27is the error i get when i use the eval
x4tje
@Vierri fixed the code.
Yacoby
@Yacoby yes it is working realy thanks for you help.
x4tje