Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have made a application using DomDocument & SimpleXML, but the server doesn't support DomDocument (Only SimpleXML). Now I am rewriting it, but there aren't any functions in SimpleXML like "getElementsByTagName" and "getElementById" (I only need those 2). I have searched a lot on php.net & google.com, but can't find one.

I am not that good to write my own. So, does anyone know a alternative/function/tip/script for me? :)

Thanks in advance.

like image 969
Crazy Monk Avatar asked Mar 26 '11 11:03

Crazy Monk


2 Answers

Happily, if SimpleXML doesn't support those DOM-methods, it supports XPath, with the SimpleXMLElement::xpath() method.

And searching by tag name or id, with an XPath query, shouldn't be too hard.
I suppose queries like theses should do the trick :

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



For example, with the following portion 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 could find one element by its id="plop" with something like this :

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

And search for all <a> tags with that :

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

And the output would be the following one :

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)
like image 188
Pascal MARTIN Avatar answered Oct 18 '22 06:10

Pascal MARTIN


Use XPath. http://www.php.net/manual/en/simplexmlelement.xpath.php

like image 32
duri Avatar answered Oct 18 '22 08:10

duri