I'm using PHP DOM and I'm trying to get an element within a DOM node that have a given class name. What's the best way to get that sub-element?
Update: I ended up using Mechanize
for PHP which was much easier to work with.
I'm using PHP DOM and I'm trying to get an element within a DOM node that have a given class name. What's the best way to get that sub-element?
Update: I ended up using Mechanize
for PHP which was much easier to work with.
DOMDocument is slow to type and phpQuery has bad memory leak issues. I ended up using:
https://github.com/wasinger/htmlpagedom
To select a class:
I hope this helps someone else as well
I think the accepted way is better, but I guess this might work as well
Update: Xpath version of
*[@class~='my-class']
css selectorSo after my comment below in response to hakre's comment, I got curious and looked into the code behind
Zend_Dom_Query
. It looks like the above selector is compiled to the following xpath (untested):[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]
so the php would be:
Basically, all we do here is normalize the
class
attribute so that even a single class is bounded by spaces, and the complete class list is bounded in spaces. Then append the class we are searching for with a space. This way we are effectively looking for and find only instances ofmy-class
.Use an xpath selector?
If it is only ever one type of element you can replace the
*
with the particular tagname.If you need to do alot of this with very complex selector i would recommend
Zend_Dom_Query
which supports CSS selector syntax (a la jQuery):If you wish to get the innerhtml of the class without the zend you could use this:
There is also another approach without the use of
DomXPath
orZend_Dom_Query
.Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.
suppose you have a variable
$html
the following HTML:use of
getElementsByClass
is as simple as: