douhui8454 2011-01-04 13:05
浏览 33
已采纳

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

I have a set of textfiles containing personal data. I want to use a script to run through them and write them to a mysql database. What I have done so far is to read the text file into a string, explode the string at " " and then run through the array to find the required information. There are a couple of problems with that though, so maybe someone knows a better solution alltogether.

The base text file looks like this:

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

The problem in this is that I have no way of knowing how long the 'value' of i.e. Street is. Could be just the 'Somestreet' or 'Some Street' or 'Some Street 1337'. This goes for pretty much every field.

Is there maybe a method to turn that text into an array, where for every item the string ending with ":" is used as the key and every following item without ending ":" is considered the value?

  • 写回答

1条回答 默认 最新

  • drls2738 2011-01-04 13:14
    关注

    As Adam hints in the comments: If there is no tab, cr/lf or similar delimiter, there is not enough information in your string to parse the data by.

    If there is only a limited set of keys, you can provide this set as additional information.
    Since you want to insert the data into a mysql table, I assume that the keys are limited and unique.
    With an array of these key strings, your parser algorithm would work this way:

    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]
    

    This should do the trick.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用