在 Javascript 变量中保存 PHP 变量时出现意外标记



我在我的Wordpress网站上有以下功能,可以在日期正确时将类放在ID上。问题是,当 Javascript 变量读取您之前使用 ID 创建的文件时,会在 Javascript 变量中创建换行符。

function ProgramarBorrado(){
    //Get day, month and year
    $date = getdate();
    $day = $date['mday'];
    $month = $date['mon'];
    $year = $date['year'];
    //Create a list
    $list = array();
    //Open/create a file
    $myfile = fopen("lista.txt", "w+");
    //If true push an ID on a list
    if(($day==5)&&($month==4)&&($year==2019)){
        array_push($list,"#borrar22marc");
    }
    if(($day==5)&&($month==4)&&($year==2019)){
        array_push($list,"#prova");
    }
    //For each value of the list, write in the file lista.txt
    foreach ($list as $value) {
        fwrite($myfile, $value."n");
    }
    //Close write mode
    fclose($myfile);
    //Open read mode
    $myfile = fopen("lista.txt", "r");
    //Get the value of each line of the file
    while(!feof($myfile)) {
      ?>
            <script>
                //Save the PHP variable on a JS variable
                var simple = '<?php echo fgetss($myfile) ;?>';
                console.log(simple);
                //Add class with jQuery
                jQuery(simple).addClass('borrar-programado');
            </script>
        <?php
        }
}
add_action('wp_footer', 'ProgramarBorrado');

这是错误:

                //Save the PHP variable on a JS variable
                var simple = '#borrar22marc
';

是的! 修剪功能是解决方案,感谢 04FS 的解决方案,这是解决方案后的代码:

function ProgramarBorrado(){
    //Get day, month and year
    $date = getdate();
    $day = $date['mday'];
    $month = $date['mon'];
    $year = $date['year'];
    //Create a list
    $list = array();
    //Open/create a file
    $myfile = fopen("lista.txt", "w+");
    //If true push an ID on a list
    if(($day==5)&&($month==4)&&($year==2019)){
        array_push($list,"#borrar22marc");
    }
    if(($day==5)&&($month==4)&&($year==2019)){
        array_push($list,"#prova");
    }
    //For each value of the list, write in the file lista.txt
    foreach ($list as $value) {
        fwrite($myfile, $value."n");
    }
    //Close write mode
    fclose($myfile);
    //Open read mode
    $myfile = fopen("lista.txt", "r");
    //Get the value of each line of the file
    while(!feof($myfile)) {
      ?>
            <script>
                //Save the PHP variable on a JS variable
                var simple = '<?php echo trim(fgets($myfile)) ;?>';
                console.log(simple);
                //Add class with jQuery
                jQuery(simple).addClass('borrar-programado');
            </script>
        <?php
        }
}
add_action('wp_footer', 'ProgramarBorrado');

最新更新