Home » Php » java – Use cURL to fetch XML and JSON data from my API

java – Use cURL to fetch XML and JSON data from my API

Posted by: admin February 25, 2020 Leave a comment


I gave myself a project that involves basic CRUD operations with Spring-boot Java as back-end and PHP as front-end. I have my API up and running, I have tested the routes with Postman and I am getting back a response depending on the header I set in postman like so. Here you can also see in my Java backend code I make sure my API can return both XML and JSON.

@GetMapping(path = "/cabbage",
        produces = {
public @ResponseBody
Iterable<CabbageFarm> getCabbageData() {
    return cabbageRepo.findAll();

The problem now for me is consuming the route with cURL in order to store the JSON or XML values I get in an array for further manipulation but when ever I do, I get NULL. Here is my php code.


    $ch = curl_init();
    $url = "localhost:8080/cabbage";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: Accept:application/json"));
    $result = curl_exec($ch);
    $data = json_decode($result, true);


In this code above I am attempting to consume JSON hence the

curl_setopt($ch, CURLOPT_HTTPHEADER, array(“Content-Type: Accept:application/json”))

How to&Answers:

Perhaps because you close curl resource too early, try to reverse these lines

curl_close($ch); $data = json_decode($result, true);

like this

$data = json_decode($result, true); curl_close($ch);