Permalink
Browse files

Added SelectorDom

  • Loading branch information...
1 parent 48cb89c commit 8d22d0d62da30e481af860bdbec307fe7e78232d @tj committed Jul 17, 2009
Showing with 39 additions and 5 deletions.
  1. +8 −0 Readme.rdoc
  2. +27 −5 selector.inc
  3. +4 −0 test.selector.php
View
@@ -33,6 +33,14 @@ The following will return an array of elements:
select_elements('ul > li ~ li', $html);
select_elements('ul > li:last-child', $html);
select_elements('li a[href=#]', $html);
+
+== SelectorDOM
+
+Persistant object for element selection.
+
+ $dom = new SelectorDOM($html);
+ $links = $dom->select('a');
+ $list_links = $dom->select('ul li a');
== Contribution
View
@@ -5,6 +5,31 @@
define('SELECTOR_VERSION', '1.0.0');
/**
+ * SelectorDOM.
+ *
+ * Persitant object for selecting elements.
+ *
+ * $dom = new SelectorDOM($html);
+ * $links = $dom->select('a');
+ * $list_links = $dom->select('ul li a');
+ *
+ */
+
+class SelectorDOM {
+ public function SelectorDOM($html) {
+ $this->html = $html;
+ $this->dom = new DOMDocument();
+ $this->dom->loadHTML($html);
+ $this->xpath = new DOMXpath($this->dom);
+ }
+
+ public function select($selector, $as_array = true) {
+ $elements = $this->xpath->evaluate(selector_to_xpath($selector));
+ return $as_array ? elements_to_array($elements) : $element;
+ }
+}
+
+/**
* Select elements from $html using the css $selector.
* When $as_array is true elements and their children will
* be converted to array's containing the following keys (defaults to true):
@@ -18,11 +43,8 @@ define('SELECTOR_VERSION', '1.0.0');
*/
function select_elements($selector, $html, $as_array = true) {
- $dom = new DOMDocument();
- $dom->loadHTML($html);
- $xpath = new DOMXpath($dom);
- $elements = $xpath->evaluate(selector_to_xpath($selector));
- return $as_array ? elements_to_array($elements, $options) : $elements;
+ $dom = new SelectorDOM($html);
+ return $dom->select($selector, $as_array);
}
/**
View
@@ -89,4 +89,8 @@ function test($selector, $expected) {
test_selector('li:nth-child(4)', 1);
test_selector('li:nth-child(6)', 0);
+$dom = new SelectorDom($html);
+print count($dom->select('a')) == 1 ? '.' : 'SelectorDOM failed';
+print count($dom->select('ul li a')) == 1 ? '.' : 'SelectorDOM failed';
+
print "\n";

0 comments on commit 8d22d0d

Please sign in to comment.