如何在PHP代码中加载json文件以准备HTTP POST? [关闭]

I have a .json file on disk. I would like to load it on my php code so that i can make an HTTP POST request with it.

I have done exactly the same with XML like this :

$file = 'http://localhost/myServer/test.xml';
$xml_builder = simplexml_load_file($file))

Then i use the $xml_builder variable to send the XML with CURL.

How can i do exactly the same with JSON ?

I think you need to do something like:

$variable = file_get_contents('http://example.com/data.json');
$decoded = json_decode($variable);

You need to decode it because you are getting it as a string in the $variable and then use it as you want

Try this

$file = '/path/to/json.json';
$json = file_get_contents($file);
$data = json_decode($json, true);

and it will result in an array of your data which you can then use however you want

Try:

$url = 'URL GOES HERE';
$file = file_get_contents('http://localhost/myServer/test.xml');

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url,
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        'xml' => $file
    )
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

//Print response
print_r('<pre>');
print_r($resp);
die();
$myJSON = file_get_contents('location/of/your/json');
// $myJSON now contains the JSON string. you can already send this with curl.

$myJSONDecoded = json_decode($myJSON);
// now $myJSONDecoded holds an array with the data. which you can use any way you like.