jonboy
jonboy

Reputation: 2749

Unable to write to json file using php

I am trying to execute a query and write the results to my title.json file.

The query is located in my lib/conn.php page, when I visit this page in my browser I can see connected, and when I look at NetBeans I can see that the file title.json has been created as it should be, however it's empty.

I am able to delete and re-create this file by visiting the lib/conn.php page, therefore there must be something wrong with my code/array?

My current code is as follows;

<?php

// Create connection
$db = new mysqli('localhost', 'MyDbUser', 'MyDbPass', 'MyDbName');

// Check connection
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}
    else{
        echo "connected </br>";
    }

$sql = ("SELECT title FROM publication");

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

$data = array();

while($row = $result->fetch_assoc()){
    $data[] = $row['title'];
}

//file_put_contents('../test.txt','Hello World. Test!'); // this works

//var_dump($data); // this works

file_put_contents('../title.json', json_encode($data));

?>

For testing purposes I have tried var_dump($data) which does print the array on screen in the following format;

array(592) { [0]=> string(206) "Some text..." [1]=> string(183) "Some text..." [2]=> string(139) "Some text..." [3]=> string(227) "Some text...

I have also run the query locally in phpmyadmin and it does return a list of titles as expected.

Any help is appreciated.

Upvotes: 0

Views: 522

Answers (1)

Jite
Jite

Reputation: 5847

PHPs json_encode docs says:

All string data must be UTF-8 encoded.

If a string is not UTF-8, json_encode will return an empty string (one could wish that it threw an exception or produced an error/warning with some... useful information instead, but well... php... hehe).
What you could try, is to encode all the strings to UTF-8 (double check so that the strings looks correct after encoding).
This is easiest done by using the utf8_encode function when you add them to the array:

while($row = $result->fetch_assoc()){
  $data[] = utf8_encode($row['title']);
}

Upvotes: 1

Related Questions