We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 4310
    • 2,310 Posts
    I’m trying to read the contents of a CSV file and enter it directly into the value field of a specific TV.
    The code below works as far as generating the the <table> layout and content from the CSV file, if I use echo/print etc. the tabled HTML content is generated okay.
    How do I get it into the DB from the $buffer ?
    I must be missing something obvious to the proper PHP coders out there!
    <?php
    $filename = "assets/files/companies.csv";
    $buffer = '';
    $buffer.='<table style="border:0; cellspacing:0; cellpadding:5; width:80%; font-size:10pt;">'."\r\n";
    $file_handle = fopen("$filename", "r");
    while (!feof($file_handle))
    {
    $rowdata = fgetcsv($file_handle, 1024);
    $buffer.= '<tr><td>'.$rowdata[0].'</td><td>'.$rowdata[1].'</td><td>'.$rowdata[2].'</td><td>'.$rowdata[3].'</td></tr>'."\r\n";
    }
    $buffer.= '</table>';
    $insert = mysql_query('INSERT INTO `modx_site_tmplvar_contentvalues` (`tmplvarid`,`contentid`, `value`) VALUES (11, 1027, "'.$buffer.'")');
    fclose($file_handle);
    ?>
      • 10449
      • 956 Posts
      use the setTemplateVar() function:
      http://code.google.com/p/modxresources/source/browse/branches/css_star_rating/star_rating.snippet.php?r=3

      But I’m wondering... is this executed only once, or in a custom module? Because it seems relatively inefficient, if the whole csv parsing is executed on every page-load. You should run this in some sort of module, and just update a chunk or TV when the csv on the server changes, i.e. when data is actually updated. btw, you can just as well write the $buffer data to a text-file on the server, and include this static file with a snippet (or @FILE with a TV).
        • 4310
        • 2,310 Posts
        Thanks for pointing out the setTemplateVar() function.
        It solved getting the formatted table data into the DB.
        The code will be used in a Module, enabling the client to upload a CSV file with the results for an event.
        I’ll do a dropdown for them to select which event the results are for, the results will then be displayed on that events page in a TV, which will be empty until they upload the CSV file.
        Thanks again smiley