1

My school project is to create a Frontend ( html+javascript with ajax calls) connected to a PHP backend that is connected to NodeJs json-server ( https://www.npmjs.com/package/json-server)

The issue I have is on my backend where I use EasyRDF PHP library to make the http request to json-server and I get the response as a string,but it looks like a json. How I can echo that response exactly the way json-server sends to that backend ( JSON format).

My php code sample:

$address="http://localhost:4000/categories"; //json-server is running on port 4000

$clienthttp=new EasyRdf\Http\Client($address);
$requestCategories=$clienthttp->request();

//string getBody() Get the response body as string
$resultJSON=$requestCategories->getBody();
echo $resultJSON; 

The response body of my PHP backend using postman is the following string:

[ { "id": 1, "name": "Boys" }, { "id": 2, "name": "Girls" } ]

I tried json_encode for the string but I get:

"[\n {\n "id": 1,\n "name": "Boys"\n },\n {\n "id": 2,\n "name": "Girls"\n }\n]"

  • `\n` is a newline character. Does [Remove new lines from string and replace with one empty space](https://stackoverflow.com/questions/3760816/remove-new-lines-from-string-and-replace-with-one-empty-space) help you? – Niellles May 23 '21 at 10:38
  • Nielles, I get this: "[ { \"id\": 1, \"name\": \"Boys\" }, { \"id\": 2, \"name\": \"Girls\" } ]" after I changed the code to this: $resultJSON=$cerere->getBody(); $resultJSON=trim(preg_replace('/\s+/', ' ', $resultJSON)); echo json_encode($resultJSON); – Alexandra-Gabriela Galiuc May 23 '21 at 10:59
  • How about `$resultJSON = str_replace('\n', '', $resultJSON);`? – Niellles May 23 '21 at 11:55
  • hello! in the end I tried what's here and I resolved my issue: https://stackoverflow.com/questions/17488207/how-to-convert-a-string-to-json-object-in-php – Alexandra-Gabriela Galiuc May 23 '21 at 12:54

0 Answers0