'getElement (s) By' in the SimpleXML PHP class, as in PHP-DomDocument?

I made an application using DomDocument and SimpleXML, but the server does not support DomDocument (Only SimpleXML). Now I am rewriting it, but in SimpleXML there are no functions like "getElementsByTagName" and "getElementById" (I only need these 2). I searched a lot on php.net and google.com but cannot find it.

I'm not so good to write my own. So does anyone know an alternative / function / tip / script for me? :)

Thanks in advance.

+4
source share
2 answers

Fortunately, if SimpleXML does not support these DOM methods, it supports XPath, SimpleXMLElement::xpath() .

And searching by tag name or id with an XPath query should not be too complicated. I suggest that queries such as abstracts should do the trick:

  • search by id: //*[@id='VALUE']
  • search by tag name: //TAG_NAME



For example, with the following part of XML and code to load it:

 $str = <<<STR <xml> <a id="plop">test id</a> <b>hello</b> <a>a again</a> </xml> STR; $xml = simplexml_load_string($str); 

You can find one element of its id="plop" with something like this:

 $id = $xml->xpath("//*[@id='plop']"); var_dump($id); 

Look for all the <a> tags with this:

 $as = $xml->xpath("//a"); var_dump($as); 

And the output will be as follows:

 array 0 => object(SimpleXMLElement)[2] public '@attributes' => array 'id' => string 'plop' (length=4) string 'test id' (length=7) array 0 => object(SimpleXMLElement)[3] public '@attributes' => array 'id' => string 'plop' (length=4) string 'test id' (length=7) 1 => object(SimpleXMLElement)[4] string 'a again' (length=7) 
+7
source

Source: https://habr.com/ru/post/1345333/


All Articles