2

let's say I have an xml file

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?

Thanks in advance

hakre
  • 193,403
  • 52
  • 435
  • 836
user765368
  • 19,590
  • 27
  • 96
  • 167
  • 3
    You could just write your own parser :) – Scott Hunter Nov 29 '11 at 20:31
  • 1
    The DOM extension is enabled by default--there is really no good reason not to use it. – mfonda Nov 29 '11 at 20:47
  • If you can use file reads and string searches, why can't you use [DOMDocument](http://php.net/manual/en/class.domdocument.php)? Is it _possible_? Sure. But the DOM classes are standard part of PHP. This question makes no sense to me. – Herbert Nov 29 '11 at 20:49

2 Answers2

3

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

  • 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?

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
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] */ }
lorenzo-s
  • 16,603
  • 15
  • 54
  • 86