简体   繁体   中英

Only variables can be passed by reference - array_walk

I'm trying to build JSON from DB table, I need to use utf8_encode() before json_encode(). I go t this error. Here is a code. What I'm doing wrong?

    <?php
$db = new PDO('mysql:host=MY_HOST;dbname=MY_DB;charset=UTF-8',  
    'MY_LOGIN', 'MY_PASS', array(  
        PDO::ATTR_EMULATE_PREPARES => false,  
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION  
    )  
);    

$stmt = $db->prepare(  
    "SELECT id,title,`fulltext`,catid,publish_state  FROM items WHERE id>:id"  
);  
$stmt->bindValue(':id', 2000, PDO::PARAM_STR);  
$stmt->execute();  
$output_arr = $stmt->fetchAll(PDO::FETCH_ASSOC);

//FOR TEST ONLY
echo 'Output:<br />';
print_r ($output_arr); //prints OK if I remove line 21 (below)

//BEFORE ENCODING TO JSON I NEED TO ENCODE TO UTF-8...
$output_encoded = array_walk(utf8_encode, $output_arr);

//AND NOW I GOT ERROR:
//Only variables can be passed by reference in line 21

//MY NEXT STEP WOULD BE:
echo json_encode($output_encoded)
?>

If you'd fix your PDO connection string, you'd already be receiving UTF-8 encoded data directly from the database:

$db = new PDO('mysql:host=MY_HOST;dbname=MY_DB;charset=utf8', ...
                                                       ^^^^

The charset is called " utf8 " in MySQL, not UTF-8. Having set this charset parameter correctly, $stmt->fetchAll(PDO::FETCH_ASSOC) will already return UTF-8 encoded data and there's no need to use utf8_encode at all.


As for your particular issue, you had the wrong syntax, it should have been:

array_walk($output_arr, 'utf8_encode')

Even that wouldn't have helped though, since the callback for array_walk needs to modify the parameter by reference, which utf8_encode does not do. You probably meant to do this:

$output_encoded = array_map('utf8_encode', $output_arr);

But even that wouldn't be correct, since $output_arr is a multidimensional array which would not be treated correctly here. And again, by fixing the PDO connection that's unnecessary anyway. In fact, do not do this when your database is already returning proper UTF-8, it'll just garble your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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