How can I do a PHP request like I already have in Python which gives me data in JSON

Issue

I have a Python script which gives me back some data in JSON. It starts a session, posts some auth data and requests data which comes back with JSON. That works fine, but can somebody help me to do this in PHP? I am sure it is possible but I am struggling to construct that.

import requests
    with requests.Session() as s:
        start_time = time.time()
        s.post('http://IP:PORT/WHATEVER/AUTH', data={'username':'jdoe','password':'forgotten'})
        req = 'http://IP:PORT/WHATEVER/DATA/BOM%20fe?table=cars,tires,&format=json'
        res = s.get(req)

Solution

you need to look for curl request in php. here is a example

function getdata($url){
    if(!function_exists("curl_init"))
        die("cURL extension is not installed");

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2&postvar3=value3");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $output = curl_exec ($ch);

    curl_close ($ch);
    return $output;
}

$output = getdata("https://website.com");
var_dump($output);

you can use json decode fuction to covert into matrix and use the variables

$arr = json_decode($output,true);

you can use something like this for formatting:

curl_setopt($ch, CURLOPT_POSTFIELDS, 
    http_build_query(array('postvar1' => 'value1')));

Answered By – frier

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published