Error creating json in php

I am trying to extract data from mysql in php and return it in json format to a controller (angular).

While json is being created, some unwanted line appears, due to which I get an error when moving json.

Below is my PHP code:

$json_response = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $row_array["name"] = $row["name"]; $row_array["quantity"] = $row["quantity"]; array_push($json_response,$row_array); } echo json_encode($json_response); 

And the following console output after printing json (the console is in the controller):

 {itemData:{"data":[{"name":"item1","quantity":"10"},{"name":"item2","quantity":"20"},{"name":"item3","quantity":"25"}] <!-- Hosting24 Analytics Code --> <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script> <!-- End Of Analytics Code --> }} 

There is json above the selected part, due to which an error occurs.

Please help me solve the problem.

+5
source share
3 answers

Well, after a little research, I can confirm that my comment is right. Your code is fine and the json string that is generated by your code is fine.

However, an unwanted line added:

 <!-- Hosting24 Analytics Code --> <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script> <!-- End Of Analytics Code --> 

Added by your server. I believe that this is a free server, and therefore they allow themselves to enter their own code on their website. They have a mechanism that adds a script to every request that is made from your server (including ajax requests).

Since this code is being added by the server, it seems that you cannot do anything in your code to overcome it. It seems that the only option is to look for another hosting company or have a paid plan.

Refresh . You can try using the exit(); function exit(); immediately after printing json string. This may interfere with the host's injection.

+4
source

Where $ conn is your mysqli connection object: -

  $query = "SELECT name, quantity FROM tablename"; if ($result = mysqli_query($conn, $query)) { $out = array(); while ($row = $result->fetch_assoc() ) { $out[] = $row; } echo json_encode($out); mysqli_free_result($result); } 
0
source

To fake JSON, you can use the small Simple JSON library for PHP .

 include('includes/json.php'); $Json = new json(); $Json->add('status', '200'); $Json->add('message', 'Success'); $Json->add("data",$json_response); $Json->send(); 
0
source

All Articles