小试QueryPath,一个实现了不少jQuery接口的PHP类库

很想写一个PHP的jQuery,但是自己精力与能力有限,于是Google一下,找到 QueryPath。

其实前几天已经找到一个,叫 simple_html_dom (SourceForge下载),不到1000行代码,很简单。有兴趣就下载看看。

基本使用方法:

require   ' src/QueryPath/QueryPath.php ' ;
//  解释HTML为DOM
qp( ' <html>...</html> ' );

//  或者加载文件
qp( ' http://www.google.com.hk/index.html ' );

如果 qp的第一个参数是 url(包括http、file),则需要以html或htm为后缀名,否则当作XML来解释,通常会解释失败,并抛出 QueryPathExtension 异常,这应该说是一个缺陷,2.1版本的代码在QueryPath.php的3903-4010行。

有了qp返回的对象,我们就可以用 PHP 以 jQuery 类似的方法来操作DOM,如选择节点,可以用CSS3选择器、parent/top/children等函数。

下载是官方手册上的一个快速入门的例子 :

<? php
require_once   ' ../src/QueryPath/QueryPath.php ' ;

//  Begin with an HTML stub document (XHTML, actually), and navigate to the title.
qp(QueryPath :: HTML_STUB ,   ' title ' )
  
//  Add some text to the title
   -> text( ' Example of QueryPath. ' )
  
//  Now look for the <body> element
   -> find( ' :root body ' )
  
//  Inside the body, add a title and paragraph.
   -> append( ' <h1>This is a test page</h1><p>Test text</p> ' )
  
//  Now we select the paragraph we just created inside the body
   -> children( ' p ' )
  
//  Add a 'class="some-class"' attribute to the paragraph
   -> attr( ' class ' ,   ' some-class ' )
  
//  And add a style attribute, too, setting the background color.
   -> css( ' background-color ' ,   ' #eee ' )
  
//  Now go back to the paragraph again
   -> parent()
  
//  Before the paragraph and the title, add an empty table.
   -> prepend( ' <table id="my-table"></table> ' )
  
//  Now let's go to the table...
   -> find( ' #my-table ' )
  
//  Add a couple of empty rows
   -> append( ' <tr></tr><tr></tr> ' )
  
//  select the rows (both at once)
   -> children()
  
//  Add a CSS class to both rows
   -> addClass( ' table-row ' )
  
//  Now just get the first row (at position 0)
   -> eq( 0 )
  
//  Add a table header in the first row
   -> append( ' <th>This is the header</th> ' )
  
//  Now go to the next row
   -> next ()
  
//  Add some data to this row
   -> append( ' <td>This is the data</td> ' )
  
//  Write it all out as HTML
   -> writeHTML();
?>

详细请参考其官网及API手册(包含在源码中):http://querypath.org/

QueryPath的基本特征:http://querypath.org/node/2

你可能感兴趣的:(jquery)