Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery-like interface for PHP?

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'd like to do things like this (all hypothetical):

 foreach (j("div > p > a") as anchor) {    // ... }   print j("#some_id")->html();   print j("a")->eq(0)->attr("name"); 

These are just a few examples.

I did as much Googling as I could but couldn't find what I was looking for. Does anyone know if something along these lines exist, or is this something I'm going to have to make from scratch myself using domxml?

like image 984
theotherlight Avatar asked Sep 01 '09 19:09

theotherlight


People also ask

Can jQuery be used with PHP?

All you need to do to use jQuery with PHP is to include the jQuery javascript file in your HTML document in the head tag.

What is $() in jQuery library?

It is common to see jQuery programs call $(document) or $(this) , for example. jQuery objects can represent more than one element in a document, and you can also pass an array of elements to $() . In this case, the returned jQuery object represents the set of elements in your array.

What is jQuery HTML?

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.


2 Answers

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); 
like image 111
karim79 Avatar answered Sep 18 '22 13:09

karim79


Doing some more hunting, I think I might've found precisely what I was looking for:

phpQuery - jQuery port to PHP

Thanks everyone for your answers, I will definitely keep them in mind for other uses.

like image 36
theotherlight Avatar answered Sep 18 '22 13:09

theotherlight