读取xml文件中的特定标记,而不使用任何类型的PHP库或扩展

时间:2020-12-17 23:55:41

let's say I have an xml file

假设我有一个xml文件

how do I read a specific tag (and all the values contained in that tag) of that xml file without using any sort of php library, with just straight PHP file read and string searching. Is that possible?

如何在不使用任何类型的php库的情况下读取该xml文件的特定标记(以及该标记中包含的所有值),只需读取直接的PHP文件和字符串搜索。那可能吗?

Thanks in advance

提前致谢

2 个解决方案

#1


3  

If you were looking for a tag X, you could use string searching for <X> and </X>. But:

如果您正在寻找标签X,则可以使用字符串搜索 和 。但:

  • there might be spaces in the tag
  • 标签中可能有空格

  • there might be a mixture of upper and lower case (though case-insensitive searching will handle that)
  • 可能有大写和小写的混合(虽然不区分大小写的搜索会处理)

  • there might be nested tags (so the first <X> shouldn't pair up with the first </X>)
  • 可能有嵌套标签(因此第一个 不应与第一个 配对)

  • the tag might appear within text that a real parser would know isn't a tag
  • 标记可能出现在文本中,真正的解析器会知道它不是标记

Why can't you use a library?

你为什么不能使用图书馆?

#2


1  

You can use regular expressions if the tag you are searching for contain only simple text. If you want only the first occurrence:

如果要搜索的标记仅包含简单文本,则可以使用正则表达式。如果您只想要第一次出现:

$matches = array();
$ret = preg_match('/<yourtag>(.*?)<\\/yourtag>/i', file_get_contents('your.xml'), $matches);
if ($ret) { /* Check for $matches[1] */ }

Or multiple occurrences:

或多次出现:

$matches = array();
$ret = preg_match_all('/<yourtag>(.*?)<\\/yourtag>/i', file_get_contents('your.xml'), $matches);
if ($ret) { /* Check for $matches[1] */ }

#1


3  

If you were looking for a tag X, you could use string searching for <X> and </X>. But:

如果您正在寻找标签X,则可以使用字符串搜索 和 。但:

  • there might be spaces in the tag
  • 标签中可能有空格

  • there might be a mixture of upper and lower case (though case-insensitive searching will handle that)
  • 可能有大写和小写的混合(虽然不区分大小写的搜索会处理)

  • there might be nested tags (so the first <X> shouldn't pair up with the first </X>)
  • 可能有嵌套标签(因此第一个 不应与第一个 配对)

  • the tag might appear within text that a real parser would know isn't a tag
  • 标记可能出现在文本中,真正的解析器会知道它不是标记

Why can't you use a library?

你为什么不能使用图书馆?

#2


1  

You can use regular expressions if the tag you are searching for contain only simple text. If you want only the first occurrence:

如果要搜索的标记仅包含简单文本,则可以使用正则表达式。如果您只想要第一次出现:

$matches = array();
$ret = preg_match('/<yourtag>(.*?)<\\/yourtag>/i', file_get_contents('your.xml'), $matches);
if ($ret) { /* Check for $matches[1] */ }

Or multiple occurrences:

或多次出现:

$matches = array();
$ret = preg_match_all('/<yourtag>(.*?)<\\/yourtag>/i', file_get_contents('your.xml'), $matches);
if ($ret) { /* Check for $matches[1] */ }