为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕姐8265434 2022-11-04 17:01:58
我只需要关于这个问题的帮助。这是我想在我的 php 输出中实现的目标,因为这是所需的结构。以 JSON 形式返回的事件对象数组。[    {        "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,然后将它传递给一个变量;function getOpportunityYearly(){    //curl here...    //I pushed all the ID in my array to the global scope}所以现在,我有我的 ID 数组:   $events = [2111,2112,2113,2114,2115];//etc   $jsonResponse = [];我想循环并从 API 调用另一个 cUrl,然后应该通过 $jsonResponse 推送我的问题是,当我从 getEventByID 传递返回的响应并将其转换为 json 时,结构不正确。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);}
查看完整描述

2 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

编辑:最终通过使用多卷曲解决了卷曲多个请求。这是事件中的教程链接 Per Id 将被处理并将调用一个 curl 请求到 API。并构造一个 assoc 数组。完成后,我将 jsonResponse 编码为 JSON。


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

}


查看完整回答
反对 回复 2022-11-04
?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

示例代码中确实存在一些语法错误。但是请尝试这个。


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


?>


查看完整回答
反对 回复 2022-11-04
  • 2 回答
  • 0 关注
  • 132 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信