亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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條經驗 獲得超14個贊

示例代碼中確實存在一些語法錯誤。但是請嘗試這個。


<?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 關注
  • 178 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號