获取 php 中之间的文本
目前我正在使用并查看了此代码 http://us.php.net/manual/en/function.xml-set-element-handler.php#85970 如何获取标签之间的文本?
我正在使用 php5 和 XML 解析器
Currently i am using and have looked through this code http://us.php.net/manual/en/function.xml-set-element-handler.php#85970
How do i get the text between tags?
i am using php5 and XML Parser
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可以解释一下:
This should explain it:
除非您知道自己在做什么,否则不要使用 PHP 的 XML 解析器 - 它是一个 SAX 解析器,需要您了解 SAX 事件的概念。除非您需要非常快速地处理非常大的 XML 文件,否则不需要它。对于 99% 的情况,您不需要使用它。根据您的问题,您只需打开一个 XML 文件并搜索特定标签并提取该标签中包含的字符串即可。为此,您应该使用 DOM 或 SimpleXML 解析器。 SimpleXML 允许您使用 XPath - 请参阅此示例代码,它的大致用途你想要的。 (如果你想使用 DOM,你必须在 PHP 网站上查找它 - 我无法发布超链接,因为我是新手 - 只是要小心不要将它与 DOMXML 混淆,DOMXML 是旧的 PHP4 XML 解析器.)
如果我误读了这篇文章,而您确实想学习如何使用 SAX 解析,Google 会提供帮助 - 但基本理论是这样的:您的代码将把整个文档作为一系列事件进行处理。每个事件将代表文档中的某些内容 - 从文档的开头开始,然后打开和关闭每个元素,解析每个属性,以及解析每个字符串。您需要有代码来监听您感兴趣的事件 - 当一个元素打开和关闭时 - 然后从中查看正在打开的元素是否是您想要的 - 如果是,您需要告诉处理文本的事件处理程序现在应该侦听文本并将您要查找的任何文本存储到变量中。完成后,您可以关闭流并对文本执行任何您想要执行的操作。
同样,根据这个问题,听起来您需要 DOM 或 SimpleXML 而不是 SAX。
Don't use PHP's XML Parser unless you know what you are doing - it's a SAX parser which requires you to understand the idea of SAX events. You don't need it unless you need to handle very large XML files very quickly. For 99% of cases, you don't need to use it. Based on your question, you are simply opening up an XML file and searching for a particular tag and extracting the strings contained in that tag. For that, you should use the DOM or SimpleXML parsers. SimpleXML lets you use XPath - see this example code which does broadly what you want. (If you want to use DOM, you'll have to look for it on the PHP site - I can't post hyperlinks as I'm a newbie - just be careful not to confuse it with DOMXML which is the old PHP4 XML parser.)
If I've misread this and you do actually want to learn how to use SAX parsing, Google will help - but the basics theory is this: your code will be processing the complete document as a series of events. Each event will represent something in the document - starting with the beginning of the document, then each element being opened and closed, each attribute being parsed, and each string being parsed. You need to have code that listens to the events you are interested in - when an element gets opened and closed - and then from that, see if the element that's being opened is the one you want - if it is, you need to then tell the event handler that handles the text that it should now listen for text and store whatever text you are looking for into a variable. When you are done, you can then close the stream off and do whatever you want to do with the text.
Again, based on the question, it sounds like you need DOM or SimpleXML not SAX.