【问题标题】:how to get key value of array with curl (php)如何使用 curl (php) 获取数组的键值
【发布时间】:2023-03-26 12:53:01
【问题描述】:

我想使用 API,但它会打印很多信息,我不知道如何获取数组的一些键值。

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

提前致谢

您好, 维耶里

【问题讨论】:

    标签: php api arrays curl


    【解决方案1】:
    //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 会更好)

    如果不是,您可能需要考虑手动解析响应数组而不是使用eval

    【讨论】:

    • 您好,谢谢您的回复,解析错误:语法错误,/var/www/clients/client5/web6/web/test.php(20) 中的意外 $end : eval()'d 代码第 1 行警告:array_keys() [function.array-keys]: 第一个参数应该是 /var/www/clients/client5/web6/web/test.php 中的数组 第 27 行是我得到的错误使用评估
    【解决方案2】:

    获取所有键和值:

    $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";
    }
    

    【讨论】:

    • 响应是字符串而不是数组。 ksortforeach 期望数组。
    猜你喜欢
    • 2014-05-29
    • 1970-01-01
    • 2012-02-02
    • 2011-08-10
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 2012-12-03
    相关资源
    最近更新 更多