how to get key value of array with curl (php)
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
//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
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";
}
精彩评论