2010-03-31 113 views
2

我想使用API​​但它會打印很多信息,我不知道如何獲得數組的幾個關鍵值。如何使用curl獲取數組的鍵值(php)

<?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); 
?> 

是我的PHP腳本,它顯示

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"))))) 

在此先感謝

問候, Vierri

回答

2
//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']); 

上面的代碼是危險,可能不應該使用,因爲它是。他們可以在響應中加入任何令人討厭的東西,你會評估它(eval行),這可能會對服務器造成不良影響。我會檢查他們是否有更好的API,不會以該格式發送回覆。 (JSON或XML效果會更好)

如果沒有,你可能需要手動considerer解析響應數組,而不是使用eval

+0

您好日Thnx您的回覆, 解析錯誤:語法錯誤,在/var/www/clients/client5/web6/web/test.php(20意想不到的$結束):eval()函數就行'd碼1 警告:array_keys()[function.array-keys]:第一個參數應該是第27行的/var/www/clients/client5/web6/web/test.php中的一個數組。 是我在使用時得到的錯誤eval – x4tje 2010-03-31 12:03:25

+0

@Vierri修復了代碼。 – Yacoby 2010-03-31 12:23:34

+0

是的,它是真正的工作謝謝你的幫助。 – x4tje 2010-03-31 12:37:39

0

要獲得所有鍵和值:

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

先手鍵列表:

$server_output = curl_exec($curl); 
ksort($server_output); 
foreach ($server_output AS $key => $val) { 
    echo "$key\n"; 
} 
+0

的響應是一個字符串不是一個數組。 'ksort'和'foreach'需要數組。 – Yacoby 2010-03-31 12:02:34