views:

1191

answers:

3

Hi guys, im pretty new to the PHP DomDocument, im reading the documentation right now and im wondering is does exixts some selectors like the ones we seen in jquery.

Well, i exmplain my situation: i have this xml file to parse every day and update a database:

Europe Bank Money Currency

That's a little snapshot:

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

so, accessing this structure with jquery-like selectors will be dead simple:

$("Cube[currency]")

and i'll retrieve all the elements 'cube' with the 'currency' attribute.

But how to do that with PHP Domdocument? How to search the elements by attribute and/or attribute value?

I only saw the getElementsByTagName and getElementsById methods.

p.s: i gave a look to xpath too, but dont seem to work with DomDocument

A: 

XPath is exactly what you are looking for, here is pretty good list of possible selectors

usoban
+2  A: 

Take a look at the DOMXPath class in PHP.
//cube[@currency] would select all elements with currency attribute.

AnalyticaL
+4  A: 

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');
SleepyCod
WOW, amazing! My only doubt is the future reability... what if the project will stop? Using DomDocument will be more safe i suppose.. but i'òll give it a try!
DaNieL
It uses DOMDocument backwards, so you should not be worry about that ;) in the end, it is just a wrapper that provide syntactic sugar for all your DOM needs...
SleepyCod
Yes, i've seen that is really 'just' an API to the php DOM's API ;)But it works like magic, even with large files.Thanks man!
DaNieL