Take the 2-minute tour ×

I have a PHP file that's running a simple check for currency conversion. It works perfectly when I run it through my browser but my goal is to build a cron. When I run the script via SSH:

php /path/to/file.php

I get the following:

PHP Warning:  json_encode(): Invalid UTF-8 sequence in argument in /path/to/file.php on line 36

Where line 36 is:

fwrite($fh, json_encode($conversions));

...where $conversions is a simple single-dimension array

Here's the file:

$conversions = array();

$currencies = json_decode(file_get_contents("/path/to/currencies.json"), true);

foreach($currencies as $cur=>$data){

    //make string to be put in API
    $string = "1USD=?".$data['code'];
    //Call Google API
    $google_url = "http://www.google.com/ig/calculator?hl=en&q=".$string;

    $ch = curl_init();  
    // set URL and other appropriate options  
    curl_setopt($ch, CURLOPT_URL, $google_url);  
    curl_setopt($ch, CURLOPT_HEADER, 0);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
    // grab URL and pass it to the browser    
    $result = curl_exec($ch);
    //Explode result to convert into an array
    $result = explode('"', $result);

    $converted_amount = explode(' ', $result[3]);
    $conversion = $converted_amount[0];
    //$conversion = $conversion * $amount;
    $conversions[$cur] = $conversion;
    if($conversion==0){ exit('0 Return Error'); }



$fh = fopen("/path/to/currency_conversions.json", 'w') or die("can't open file");
fwrite($fh, json_encode($conversions));
share|improve this question
So what's in the $conversions array? Some text? random binary garbage? –  Marc B Jul 25 '12 at 15:02
It's a series of country codes (key) with their conversion rates (val) like: USD=>1,CAD=>1.23,EUR=>1.05 ... –  Fluidbyte Jul 25 '12 at 15:03
We need to see with what and how $conversions is being populated. Is it being populated from the command line arguments? From a database? Are your filesystem and database in UTF-8 encoding or are they in latin? –  Micah Carrick Jul 25 '12 at 15:05
I've added the full code to my question. –  Fluidbyte Jul 25 '12 at 15:07
add comment

2 Answers

up vote 1 down vote accepted

Well, I searched for you and I found the json_encode acceptes only UTF-8 so here is the solution:

    $conversions[$i] = utf8_encode($conversions[$i]);
fwrite($fh, json_encode($conversions));
share|improve this answer
Had to modify a bit to maintain keys, but the utf8_encode worked great. Thanks. –  Fluidbyte Jul 25 '12 at 15:11
You welcome, please mark my question as accepted :D –  Yehonatan Jul 25 '12 at 15:13
add comment

Try updating your PHP version to a version later than version 5.2.7 Older version have UTF-8 bugs.

share|improve this answer
add comment

Your Answer


