php读取产品数据txt文件
我有一个包含产品数据的 .txt 文件,我想在 php 中读取该文件。 每行包含一种产品,产品详细信息(编号、名称和价格)由制表符分隔。 正如您在下面所看到的,由于产品名称的长度不同,价格并不总是能很好地垂直对齐。 数据看起来像这样:(
ABC001 an item description $5.50
XYZ999 an other item $6
PPP000 yet another one $8.99
AKA010 one w a longer name $3.33
J_B007 a very long name, to show tabs $99
我不知道如何显示选项卡,所以它们在上面的示例中是空格,但在真实文件中,它是真正的选项卡)
最有效的方法是什么? (顺便说一句,它是一个远程文件)我希望有一个包含每个产品的产品数据的数组:
$product['number'], $product['name'] and $product['price']
非常感谢!
I have a .txt file with product data, which I want to read in php. Each line contains one product, and the product details (number, name and price) are separated by tabs. As you can see below, it is not always true that the prices are nicely aligned vertically, because of the difference in length for the prodcut names. The data look like this:
ABC001 an item description $5.50
XYZ999 an other item $6
PPP000 yet another one $8.99
AKA010 one w a longer name $3.33
J_B007 a very long name, to show tabs $99
(I didn't know how to show the tabs, so they are spaces in the example above, but in the real file, it are real tabs)
What is the most efficient way to do this? (by the way, it is a remote file) I would love to have an array containing the product data per product:
$product['number'], $product['name'] and $product['price']
Thanks very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以逐行读取文件(使用函数
file
,例如,这将使您将每一行放入数组的一行中)。然后,在每一行上使用
explode
来分隔字段:使用“
\t
”(制表”)作为分隔符。然后您将得到包含数字
$data_of_line[1]< 的
$data_of_line[0]
/code> 名称,$data_of_line[2]
价格。You could read the file line by line (using the function
file
, for instance, that will get you each line into one line of an array).And, then, use
explode
on each of those lines, to separate the fields :Using "
\t
" (tabulation") as a separator.You'd then have
$data_of_line[0]
containing the number,$data_of_line[1]
the name, and$data_of_line[2]
the price.1)最简单的方法是使用 file() 将所有行加载到数组中(除非文件真的很大,那么我会考虑另一种方法)。
2) 按制表符(“\t”字符)分割每一行
3) 根据需要“格式化”数组列。
示例片段:
1) Easiest way is using file() to load all the lines into an array (unless the file is really big, then i would consider another approach).
2) split each line by tab ("\t" character)
3) "format" the array columns as you wish.
Sample snippet:
fgetcsv() 是一个很好的函数,
查看示例
https://www.php.net/manual/en/function.fgetcsv。 php,这是一个稍加修改的版本:
fgetcsv() is a good function
check out the example from
https://www.php.net/manual/en/function.fgetcsv.php, here's a slightly modified version:
这会比使用explode慢一些,但它也可以解析具有多个选项卡作为值之间分隔符的文件。 另外,您不必从价格中删除
$
符号。 如果您不想在价格中保留$
符号,则应使用此正则表达式:This will be slower the using explode but it can also parse files that have more then just one tab as a separator between values. Plus you won't have to strip
$
sign from the prices. If you wan't to keep$
sign with the price you should use this regex instead: