Querying SimpleXML object with CSS selectors instead of XPath
I'm using SimpleXML to load and parse an XML document with PHP.
I'm not too familiar with XPath and I would prefer using CSS selectors to parse it. What are my options? Is there anything pre-build for Simpl开发者_Go百科eXML, or should I be using something different altogether ?
SimpleXML doesn't support CSS selectors, but I know that some PHP and Javascript librairies can convert a CSS selector to an XPath query. IIRC, there's a PHP library that mimicks jQuery's selectors but I can't remember its name. Hopefully it will jumpstart someone else's memory.
Turns out the library I was thinking about doesn't support CSS selectors, but the good news is the Zend Framework has a CSS-to-XPath translator:
include 'Zend/Dom/Query/Css2Xpath.php';
$xpath = Zend_Dom_Query_Css2Xpath::transform('div.class span');
$mySimpleXMLElement->xpath($xpath);
The Zend CSS-to-XPath translator is not full proof. It fails for index selectors - something like tr:eq(1) will not be converted to tr[2]
精彩评论