如何将这种SQL格式的表格转换为CSV格式?

fnvucqvd  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(231)

有什么建议可以将从SQL中提取的文本文档转换为CSV吗?这是针对WordPress用户元数据表的。
数据遵循以下格式:

(1,1,'nickname','person1'),(2,1,'first_name','person1name'),(3,1,'last_name','person1lastname'),(4,1,'description','yyy')

(1,2,'nickname','person2'),(2,2,'first_name','person2name'),(3,2,'last_name','person2lastname'),(4,2,'description','xxx')

等等,只不过它们都在一行中。
我想要

User_ID,nickname,first_name,last_name,description
1,person1,person1name,person1lastname,yyy
2,person2,person2name,person2lastname,xxx

我试过把它放在SQL到CSV转换器中,他们不接受。VS代码似乎也不把它解释为一个有效的SQL表。
任何帮助都将不胜感激。
谢谢你!

ljsrvy3e

ljsrvy3e1#

试试这个

<?php

$str = "(1,1,'nickname','person1'),(2,1,'first_name','person1name'),(3,1,'last_name','person1lastname'),(4,1,'description','yyy')
(1,2,'nickname','person2'),(2,2,'first_name','person2name'),(3,2,'last_name','person2lastname'),(4,2,'description','xxx')";

function sqlConvertToCSV($sqlValuesNotationRows) {
    
    //replace new line to comma
    $santize_str = preg_replace('/\n/',',',trim($sqlValuesNotationRows));

    //Changes ( ) for [ ]. Heads up! Don't take into account the presence of characters inside the values, you may need to use a better regex here...
    $lines = str_replace(['(',')', '\''], ['[',']','"'], $santize_str);
    
    // Convert JSON notation to ARRAY
    $array_items = json_decode("[". $lines ."]");
    
    //Return array list
    //return $array_items;
    
    // implode for create lines of CSV
    $csv = implode("\n", array_map(function($line){
        return implode(",", $line);
    }, $array_items));
    
    // Return csv lines
    return $csv;
}

print_r(sqlConvertToCSV($str));

输出

1,1,nickname,person1
2,1,first_name,person1name
3,1,last_name,person1lastname
4,1,description,yyy
1,2,nickname,person2
2,2,first_name,person2name
3,2,last_name,person2lastname
4,2,description,xxx

相关问题