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 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile