PHP脚本将文件文本传输到数据库

时间:2011-01-04 13:05:55

标签: php arrays string text

我有一组包含个人数据的文本文件。我想使用脚本来运行它们并将它们写入mysql数据库。 到目前为止,我所做的是将文本文件读入字符串,在“”处展开字符串,然后遍历数组以查找所需信息。但是有一些问题,所以也许有人知道一个更好的解决方案。

基本文本文件如下所示:

Name: Marius
Address 1: Street
Address 2: Town
Address 3: Country
etc

问题在于我无法知道街道的“价值”有多长。可能只是'Somestreet'或'Some Street'或'Some Street 1337'。这几乎适用于每个领域。

是否有一种方法可以将该文本转换为数组,其中对于每个项目,以“:”结尾的字符串用作键,而后面的每一项不带“:”的项都被视为值?

1 个答案:

答案 0 :(得分:2)

正如Adam在评论中暗示:如果没有tab,cr / lf或类似的分隔符,则字符串中没有足够的信息来解析数据。

如果只有一组有限的按键,您可以将此组作为附加信息提供 由于您要将数据插入到mysql表中,我假设键是有限且唯一
使用这些关键字符串的数组,您的解析器算法将以这种方式工作:

1 explode the string at ":"
2 loop through the resulting array, where you should find a structure like this:
    [some or no value][space or other delimiter][known key]
2.1 remember the key from the previous loop (empty as default)
2.2 since the keys should be unique, loop through the array of known keys
2.2.1 if a key matches the current string structure from the right, you can 
    strip this key off the right side of the string, trim the string and you
    have the current value
2.2.2 if you found a value, put both into the result array: 
    $arr[previous key] = [current value]

这应该可以解决问题。