简体   繁体   中英

Concatenate string into file_put_contents

I want to write both a string and an array to a file using file_put_contents in php. To write the array, I'm able to do:

file_put_contents('filename.js', json_encode(array(
    'status'    => TRUE,
    'data'      => $data
), JSON_NUMERIC_CHECK));

The resulting file then appears as:

{status:true,data:dataArray}

I would simply like to put a string before that array in the file so that it reads:

var myData = {status:true,data:dataArray}

I've tried the following unsuccessfully:

file_put_contents('all_model_data.js', json_encode("var myData =", array(
    'status'    => TRUE,
    'data'      => $data
), JSON_NUMERIC_CHECK));

And

file_put_contents('all_model_data.js', ("var myData =", json_encode(array(
    'status'    => TRUE,
    'data'      => $data
), JSON_NUMERIC_CHECK)));

Any tips? Thanks,

The first line should read:

file_put_contents('all_model_data.js', "var myData =". json_encode(array(

String concatenation in PHP is performed with the dot operator.

Try

file_put_contents('all_model_data.js', 'var myData = ' . json_encode(array(
'status'    => TRUE,
'data'      => $data
), JSON_NUMERIC_CHECK));

OR use FILE_APPEND

file_put_contents('all_model_data.js', 'var myData = ');
file_put_contents('all_model_data.js', json_encode(array(
        'status' => TRUE,
        'data' => $data
), JSON_NUMERIC_CHECK), FILE_APPEND);

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