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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
classattribute 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 a lot of this with very complex selector I would recommend
Zend_Dom_Querywhich supports CSS selector syntax (a la jQuery):