简体   繁体   English

PHP Cron Job json_encode错误

[英]PHP Cron Job json_encode error

I have a PHP file that's running a simple check for currency conversion. 我有一个PHP文件,正在对货币换算进行简单检查。 It works perfectly when I run it through my browser but my goal is to build a cron. 当我通过浏览器运行它时,它可以完美运行,但我的目标是建立一个cron。 When I run the script via SSH: 当我通过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: 第36行是:

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

...where $conversions is a simple single-dimension array ...其中$ conversions是一个简单的一维数组

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'); }

    curl_close($ch);

}

$fh = fopen("/path/to/currency_conversions.json", 'w') or die("can't open file");
fwrite($fh, json_encode($conversions));
fclose($fh);

Well, I searched for you and I found the json_encode acceptes only UTF-8 so here is the solution: 好吧,我搜索了您,发现json_encode仅接受UTF-8,因此这是解决方案:

for($i=0;$i<count($conversions);$i++)
    $conversions[$i] = utf8_encode($conversions[$i]);
fwrite($fh, json_encode($conversions));

尝试将您的PHP版本更新为高于5.2.7的版本。较早的版本具有UTF-8错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM