-4

I have a tab delimited text(string) in a text area. For instance the user would just paste the result set from a SQL query into this text area directly with headers.

What would be the ideal way to read this input and convert into an array either in php or javascript. I eventually want to convert this into json using json_encode.

Help appreciated!!

oyeesh
  • 551
  • 9
  • 21
  • 3
    http://stackoverflow.com/questions/1792950/explode-string-by-one-or-more-spaces-or-tabs – Jeff Dec 29 '16 at 02:24
  • [`google php convert tab delimited string to array`](http://stackoverflow.com/questions/16288589/converting-a-texttab-delimited-to-php-associative-array-instead-of-this-code) – Kevin Dec 29 '16 at 02:24

1 Answers1

0

Something like this should work:

<?php

if ($_POST) {
    $data = trim($_POST['pastedData']);

    $tabDelimitedLines = explode("\r\n", $data);
    $myArray = Array();

    foreach ($tabDelimitedLines as $lineIndex => $line) {
        $fields = explode("\t", $line);

        foreach ($fields as $fieldIndex => $field) {

            if ($lineIndex == 0) {
                // assuming first line is header info
                $headers[] = $field;
            } else {
                // put the other lines into an array
                // in whatever format you want

                $myArray[$lineIndex - 1][$headers[$fieldIndex]] = $field;
            }
        }
    }

    $json = json_encode($myArray);

    echo "Associative Array in PHP:<br>";
    echo "<pre>";
    var_dump($myArray);
    echo "</pre>";
    echo "JSON:<br>";
    echo $json;
    echo "<br><br>";
}
?>
<html>
<form method="post">
    <label>Paste some Tab Delimited Data with Headers:</label><br>
    <textarea name="pastedData"></textarea><br><br>
    <button type="submit">Submit</button>
</form>
</html>
BizzyBob
  • 12,309
  • 4
  • 27
  • 51