Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
+3 votes
485 views
in Q2A Core by
How can I import questions from a .txt file? Every question is put per line in the .txt file. Example:

 

How to 1...

How to 2....

How to 3....

How to 4...

 

Can I import these?

 

Thanks in advance
Q2A version: last version

1 Answer

+2 votes
by
edited by

I know I'm late to the party but I'm answering still for future viewers.

You can use this code from docs.question2answer.org/code/external to add a question:

    <?php
    require_once '/PATH/TO/qa-include/qa-base.php';

    require_once QA_INCLUDE_DIR.'qa-app-users.php';
    require_once QA_INCLUDE_DIR.'qa-app-posts.php';

    $type = 'Q'; // question
    $parentid = null; // does not follow another answer
    $title = 'Why do birds sing?';
    $content = 'And why do they fall in love?';
    $format = ''; // plain text
    $categoryid = null; // assume no category
    $tags = array('birds', 'sing', 'love');
    $userid = qa_get_logged_in_userid();

    qa_post_create($type, $parentid, $title, $content, $format, $categoryid, $tags, $userid);

All you need to do now is add code to read the questions in the text file into an array and then loop through it to add all the questions using qa_post_create.

This answer might help too:

http://www.question2answer.org/qa/1222/what-is-the-best-way-for-me-to-upload-lot-of-questions-to-the-db for more

Update:

I ended up writing the code for it here:

<?php
require_once '
your_base_folder_path/qa/qa-include/qa-base.php';
require_once QA_INCLUDE_DIR.'qa-app-users.php';
require_once QA_INCLUDE_DIR.'qa-app-posts.php';

function readCSV($csvFile) {
    $file_handle = fopen($csvFile, 'r');
    $count = 0;
    $line_of_text = array();
    while (!feof($file_handle) ) {
        $count++;
        $line_of_text[] = fgetcsv($file_handle, 0);
    }
    echo '<br/>read '.$count.' lines<br/>';
    fclose($file_handle);
    return $line_of_text;
}

try {
    $csv = readCSV('
source_file.csv');
    $userid = qa_get_logged_in_userid();
    $categoryid = 
yourCategoryId; // use null for no category
    $count = 0;

    foreach ($csv as $c) {
        $type = 'Q'; // question
        $parentid = null; // does not follow another answer
        $title = $c[0];
        $content = trim($c[1]);
        $format = ''; // plain text
        $tags = array('some-tag', 'some-other-tag');
        qa_post_create($type, $parentid, $title, $content, $format, $categoryid, $tags, $userid);
        echo($title.'<br/>'.$content.'<br/><br/>');
    }
}
catch(Exception $e) {
    echo 'Message: ' .$e->getMessage();
}
echo 'done!';

?>

Note that you'll need to strip out the header row form the csv file so it doesn't net imported as well.

...