Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery-like selectors for PHP DOMDocument

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.

like image 311
Strae Avatar asked Jul 14 '09 09:07

Strae


2 Answers

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');
like image 163
Christophe Eblé Avatar answered Sep 28 '22 15:09

Christophe Eblé


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.

like image 29
AnalyticaL Avatar answered Sep 28 '22 17:09

AnalyticaL