I was curious as to whether or not there exists a jQuery-style interface/library for PHP for handling HTML/XML files -- specifically using jQuery style selectors.
I\
Have you looked into using PHP's DOMDocument class?
http://us2.php.net/manual/en/book.dom.php
Not sure if this is exactly what you're looking for, but it does allow for searching a document by various attributes, and other such DOM manipulation.
PHP Simple HTML DOM Parser uses jQuery-style selectors. Examples from the documentation:
Modifying HTML elements:
// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$html->find('div', 1)->class = 'bar';
$html->find('div[id=hello]', 0)->innertext = 'foo';
echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>
Scraping Slashdot:
// Create DOM from URL
$html = file_get_html('http://slashdot.org/');
// Find all article blocks
foreach($html->find('div.article') as $article) {
$item['title'] = $article->find('div.title', 0)->plaintext;
$item['intro'] = $article->find('div.intro', 0)->plaintext;
$item['details'] = $article->find('div.details', 0)->plaintext;
$articles[] = $item;
}
print_r($articles);
The question is old but what you need is Query Path.
I wrote a library that duplicates jQuery's DOM manipulation methods in PHP, but it uses xpath, not the jquery style selectors. Otherwise, it works pretty much the same.
[http://pxtreme.sourceforge.net][1]
$doc = px("index.html"); // Create a px Object
$headings=$doc->xpath("/html/body/h2"); // Select Elements to Manipulate
$headings->addClass("NewLook"); // Change their Appearance
px("index.html")->xpath("//h2")->addClass("NewLook"); // All in One Line
// use anonymous functions in PHP 5.3
$doc->xpath("//p")->each( function ($pxObject, $index) {
$str = $pxObject->get($index)->text();
if (mb_strpos($str, "pxtreme"))
$px->attr("title", "Check out this paragraph!");
});
http://pxtreme.sourceforge.net
If you use a modern framework, you should check these out too.
These components can be installed via composer.
Trust me you are looking for xPath. I am showing you an example
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?php
$dom = new DOMDocument;
libxml_use_internal_errors(TRUE);
$dom->loadHTMLFile('http://somewhereinblog.net');
libxml_clear_errors();
$xPath = new DOMXPath($dom);
$links = $xPath->query('//h1//a'); //This is xPath. Really nice and better than anything
foreach($links as $link) {
printf("<p><a href='%s'>%s</a></p>\n", $link->getAttribute('href'), $link->nodeValue);
}
?>