#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2002
    Posts
    35
    Rep Power
    12

    process newlines for javascript


    I need to pass contents of textfile to a javascript variable to be used to repopulate a textarea box. The text file has multiple lines. Using the code below I get an unterminated string constant error.


    echo "<script language='javascript'>";
    echo "function setTextFieldValue() {";
    echo "parent.control.report.value='";

    readfile("numbers.txt");

    echo "';";
    echo "}";
    echo "</script>";

    and the outputted javascript looks like:

    <script language='javascript'>function setTextFieldValue() {parent.control.report.value='9
    8
    7
    6';}</script>

    I understand that I need the variable in the javascript to look like "9\n8\n7\n6" but can't figure out how to make that happen. Even when I get rid of readfile and set the value manually to "9\n8\n7\n6" I get the same output and error.

    Per other threads I have experimented with things like:

    $db_remark = addslashes($db_remark);
    $db_remark = str_replace("\n","\\n",$db_remark);
    $db_remark = str_replace("\r","\\r",$db_remark);

    but have not had success.
    Jeff
  2. #2
  3. /(bb|[^b]{2})/

    Join Date
    Nov 2001
    Location
    Somewhere in the great unknown
    Posts
    5,163
    Rep Power
    792
    Don't use readfile(). Use file() instead and store the variable in a string, then do the string replace on it. i.e.
    PHP Code:
    $file=file('numbers.txt');
    $file=implode('',$file);
    $file=str_replace("\n","\\\n",$file);
    $file=str_replace("\r","\\\r",$file); 
    [edit]gotta love the parsing engince here. The second argument should have 2 slashes.[/edit]
    Last edited by Onslaught; August 4th, 2002 at 04:44 PM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Oct 2000
    Location
    Back in the real world.
    Posts
    5,966
    Rep Power
    190
    instead of
    readfile("numbers.txt");

    use:
    $lines=file("numbers.txt"); // read the file into an array
    $oneline=implode('\n',$lines); // make a string of this array
    echo $oneline;
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2002
    Posts
    35
    Rep Power
    12

    many thanks


    Thanks much - that was an even better solution than I was hoping for. I have to reverse the order of the text file anyway so the array works great.
    Jeff

IMN logo majestic logo threadwatch logo seochat tools logo