在 PHP 中处理字符串时出现意外结果
感谢您抽出时间帮我查看此内容。
背景:我正在处理个人理财项目的 OFX/QFX 文件。我用 C# 编写了代码,它执行得很好。我能够创建导入对象,逐行处理 OFX/QFX 文件并将上述对象输出到控制台。不过,我将其移植到 PHP,以便在不是在 .Net Framework 上编写的 Web 应用程序中使用。
问题:用户上传文件并传递到我的 PHP 文件。当使用 $line = fgets($file); 逐行读取文件时,我没有得到预期的结果。我知道文件已打开并且正在读取该行。然而;当我在分配变量后立即放置 var_dump($line)
时,我收到 "string(15) "ENG ""
当我应该得到的是:
<LANGUAGE>ENG
我的处理模型很大程度上取决于读取字符串标签部分的能力,但因为 PHP 似乎正在将其剥离,我的代码没有按预期执行。
问题:谁能告诉我为什么在使用 fgets() 时没有收到完整的字符串值?还有更正确的方法吗?我对 .Net 非常了解,但 PHP 对我来说有点陌生,所以我假设这只是我不理解的 PHP 语言的一个怪癖。
谢谢
Thank you for your time to look at this for me.
Background: I am processing OFX/QFX files for a personal finance project. I have written the code in C# and it executes perfectly. I am able to create my import object, process the OFX/QFX file line by line and output the a fore mentioned object to the console. However I am porting this to PHP for use in a web application that is not written on the .Net Framework.
Problem: A file is uploaded by a user and passed to my PHP file. When reading the file line by line using $line = fgets($file);
I am not getting the expected results. I know for a fact that the file is open and that the line is being read. However; when I put var_dump($line)
immediately after the variable is assigned I receive"string(15) "ENG ""
when what I should get is:
<LANGUAGE>ENG
My processing model heavily depends on the ability to read the tag portion of the string, but because PHP seems to be stripping it out, my code does not perform as expected.
Question: Can anyone tell me why I am not receiving the full string value when using fgets()? Also is there a more correct way to do this? I am quite knowledgeable in .Net but PHP is a little new to me so I'm assuming it's just a quirk of the PHP language that I do not understand.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题在于
被浏览器解析,被视为无效的 HTML 标记并被忽略。右键单击浏览器中的“查看源代码”以查看实际输出。
The problem is that
<LANGUAGE>
is parsed by the browser, considered an invalid HTML tag and ignored.Right-click view source in the browser to view the real output.
正如您在 var_dump() 结果中看到的,它是一个 15 个字符长的字符串。您的问题可能是
标记未显示,而是显示在“那里”。尝试使用
htmlspecialchars($line);
代替。但我通常建议使用 var_dump(),因为它非常清楚地显示变量值的类型和长度。As you can see with your var_dump() result, it's a 15 char long string. Your problem is probably that the
<LANGUAGE>
tag is not shown but "there".Try using
htmlspecialchars($line);
instead. But I normally recommend the usage of var_dump(), since it shows very clearly the type and the length of a variable value.我大胆猜测
ENG
是否是您期望输出到屏幕的内容,那么它可能就是这样。您的网络浏览器将看到它并尝试将其解析为标签,并且仅显示与该标签关联的数据,而不显示标签本身。 PHP 不是问题。尝试使用 pre 标签回显该行I would venture to guess if
<LANGUAGE>ENG
is what you are expecting to be outputted to the screen then it probably is. Your web browser will see that and attempt to parse it as a tag and only display the data associated with that tag and not the tag itself. Not an issue with PHP. Try echoing the line using pre tags