I'm working with a DOMDocument
, and I'm wondering if there exists some way of using CSS-like selectors to select nodes like we would in jQuery.
Example situation: I'm parsing an XML file, one snippet of which looks like this:
<gesmes:Envelope>
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2009-07-13">
<Cube currency="USD" rate="1.3975"/>
<Cube currency="JPY" rate="129.03"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="26.028"/>
</Cube>
</Cube>
</gesmes:Envelope>
Accessing this structure with jQuery-like selectors would be dead simple. For example, I could use
$("Cube[currency]")
to retrieve all the Cube
elements with the 'currency' attribute.
But how can I do the same thing with PHP's DOMDocument
? I'd like to select elements which have an attribute, or have a particular attribute value.
If you want to manipulate the DOM ala Jquery, PHPQuery is something for you.
http://code.google.com/p/phpquery/
A simple example of what you can do with it.
// almost everything can be a chain
$li = null;
$doc['ul > li']
->addClass('my-new-class')
->filter(':last')
->addClass('last-li');
Take a look at the DOMXPath
class in PHP. It uses XPath, so you'll need to read up on XPath syntax if you're unfamiliar with it. There's some documentation on MSDN, or you can read the W3 spec if you're particularly brave.
To solve your example problem: //cube[@currency]
is an XPath query that selects all elements in the document with a currency attribute. Usage of this with the DOMXPath
class would look like this:
$xpath = new DOMXpath($myDomDocument);
$cubesWithCurrencies = $xpath->query('//cube[@currency]');
$cubesWithCurrencies
is now a DOMNodeList
that you can iterate over.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With