首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在php中创建cURL响应中对象的json

如何在php中创建cURL响应中对象的json
EN

Stack Overflow用户
提问于 2020-03-19 13:38:42
回答 2查看 191关注 0票数 3

我只是需要关于这个问题的帮助。以下是我想要在php输出中实现的内容,因为这是所需的结构。以JSON形式返回的事件对象数组。

代码语言:javascript
运行
复制
[
    {
        "page_item_url":"2111",
        "data":{
            "startTime":"11:00"
            "endTime":"12:00",
            "summary":"<p>This has html tags in it from API<p>"
        }
    },{
        "page_item_url":"2112",
        "data":{
            "startTime":"11:00"
            "endTime":"12:00",
            "summary":"<p>This has html tags in it from API<p>"
        }
    }
]

返回的JSON应该是这样的,它是一个使用cUrl的API的调用。我有一个函数,它首先获取所有的ID,然后将其传递给一个变量;

代码语言:javascript
运行
复制
function getOpportunityYearly(){
    //curl here...
    //I pushed all the ID in my array to the global scope
}

现在,我有了我的ID数组:

代码语言:javascript
运行
复制
   $events = [2111,2112,2113,2114,2115];//etc
   $jsonResponse = [];

在其中,我想循环并从API调用另一个cUrl,然后应该通过$jsonResponse推送它。我的问题是,当我传递从getEventByID返回的响应并将其转换为json时,结构不正确。

代码语言:javascript
运行
复制
for($i=0;$i<count($events);$i++){
    getEventByID($events[$i]);
}

function getEventByID($eventID){
    curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_URL =>'https://sampleapi.com/api/v3/data/opportunities/'.$eventID.'?key='.$GLOBALS['API_KEY'].'&fields=["startTime","endTime","physicalDifficulty","summary"]&where={"whereType":"AND","clauses":[{"fieldName":"displayToPublic","operator":"checked"}]}',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",

    $response = json_decode(curl_exec($curl));
    curl_close($curl);
    $record = $response->records[0];

    return json_encode([[
      "page_item_url"=> $record->opportunities_id->value,
        "data"=>[
          "startTime"=>$record->startTime->displayValue,
          "endTime"=>$record->endTime->displayValue,
          "summary"=>$record->summary->displayValue,
          ]
    ]],JSON_HEX_QUOT | JSON_HEX_TAG);

}

从getEventByID函数返回的应该是一个json格式,格式类似于上面的json示例。当我尝试将从getEventByID返回的代码用于单个对象时,可以查看https://prnt.sc/ris9g7,但是当我首先将响应推送到全局数组变量,然后对其进行编码时,得到的结果类似于以下https://prnt.sc/risjw5

我尝试创建一个数组并推送所有从getEventByID返回的内容,但输出不是JSON字符串,而是一个数组。我是不是做错了什么。

当我使用forloop时,页面速度很慢,并且获得了30秒的最大超时,我尝试使用$curl,CURLOPT_TIMEOUT_MS并将其设置为5分钟。但是,有没有其他方法可以让这个cURL不变慢呢?或者这是正常的,因为我们从API获取所有的ID events对象?你有什么建议可以改善这一点吗?

这是从getEventByID https://prnt.sc/ris8zx返回的类型这是我如何从curl响应https://prnt.sc/ris9c0构造和返回单个事件的方法这是正确的,我得到了https://prnt.sc/ris9g7如果我去掉json_encode中的括号,只传递一个键值的assoc数组,然后将它推入一个数组

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-19 14:04:44

编辑:最终使用multi解决了curl的多个请求。下面是事件中的每个Id的教程link将被处理,并将调用一个curl请求。并构造一个assoc数组。完成后,我已经将jsonResponse编码为JSON。

代码语言:javascript
运行
复制
function multiCurl($eventArray){
    // array of curl handles
    $multiCurl = array();

    // data to be returned
    $result = array();

    // multi handle
    $mh = curl_multi_init();

    foreach ($eventArray as $event) {
        //$event are the ID per each event
        // URL from which data will be fetched
       // $curl = curl_init();
        $multiCurl[$event] = curl_init();
        curl_setopt_array($multiCurl[$event], array(
          CURLOPT_URL =>'https://api.civicore.com/voc/api/v3/data/opportunities/'.$event.'?key='.$GLOBALS['API_KEY'].'&fields=["opportunityName","typeOfWork","firstDateInOpportunity","lastDateInOpportunity","startTime","endTime","physicalDifficulty","minimumAge","location","state","city","county","campingAvailable","groupsAllowed","registrationFormID","cRQ_payment","paymentAmount","additionalInformation","photo","displayToPublic","latitude","longitude","summary","description","photo"]&where={"whereType":"AND","clauses":[{"fieldName":"displayToPublic","operator":"checked"}]}',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET"
        ));
        curl_multi_add_handle($mh, $multiCurl[$event]);
    }

    do {
      curl_multi_exec($mh,$index);
    } while($index > 0);

      // get content and remove handles
      foreach($multiCurl as $key=>$value) {

        $records = json_decode(curl_multi_getcontent($value));//response of each request
        $record  = $records->records[0];

       if(strtolower($record->displayToPublic->displayValue) == 'yes'){
          $eve =  [ 
            "page_item_url"=> $record->opportunities_id->value,
              "data"=>[
                "startTime"=>$record->startTime->displayValue,
                "endTime"=>$record->endTime->displayValue,
                "summary"=> $record->summary->displayValue
                ]
              ];
          array_push($GLOBALS["jsonResponse"],$eve);
        }
        curl_multi_remove_handle($mh, $value);
      }//foreach
    curl_multi_close($mh);
}
票数 2
EN

Stack Overflow用户

发布于 2020-03-19 13:56:07

在示例代码中确实有一些语法错误。不过,请试试这个。

代码语言:javascript
运行
复制
<?php
function getEventByID($eventID)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://sampleapi.com/api/v3/data/opportunities/' . $eventID . '?key=' . $GLOBALS['API_KEY'] . '&fields=["startTime","endTime","physicalDifficulty","summary"]&where={"whereType":"AND","clauses":[{"fieldName":"displayToPublic","operator":"checked"}]}',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
    ));
    $response = json_decode(curl_exec($curl));
    curl_close($curl);
    $record = $response->records[0];

    return json_decode(json_encode([
        "page_item_url" => $record->opportunities_id->value,
        "data" => [
            "startTime" => $record->startTime->displayValue,
            "endTime" => $record->endTime->displayValue,
            "summary" => $record->summary->displayValue,
        ]
    ], JSON_HEX_QUOT | JSON_HEX_TAG));
}

$events = [2111, 2112, 2113, 2114, 2115]; //etc
$jsonResponse = [];

for ($i = 0; $i < count($events); $i++) {
    $jsonResponse[] = getEventByID($events[$i]);
}

print_r($jsonResponse);

?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60751496

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档