免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2670 | 回复: 0
打印 上一主题 下一主题

小试QueryPath,一个实现了不少jQuery接口的PHP类库 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-06-21 17:09 |只看该作者 |倒序浏览
小试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等函数。


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

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

  3. // Begin with an HTML stub document (XHTML, actually), and navigate to the title.
  4. qp(QueryPath::HTML_STUB, 'title')
  5.   // Add some text to the title
  6.   ->text('Example of QueryPath.')
  7.   // Now look for the <body> element
  8.   ->find(':root body')
  9.   // Inside the body, add a title and paragraph.
  10.   ->append('<h1>This is a test page</h1><p>Test text</p>')
  11.   // Now we select the paragraph we just created inside the body
  12.   ->children('p')
  13.   // Add a 'class="some-class"' attribute to the paragraph
  14.   ->attr('class', 'some-class')
  15.   // And add a style attribute, too, setting the background color.
  16.   ->css('background-color', '#eee')
  17.   // Now go back to the paragraph again
  18.   ->parent()
  19.   // Before the paragraph and the title, add an empty table.
  20.   ->prepend('<table id="my-table"></table>')
  21.   // Now let's go to the table...
  22.   ->find('#my-table')
  23.   // Add a couple of empty rows
  24.   ->append('<tr></tr><tr></tr>')
  25.   // select the rows (both at once)
  26.   ->children()
  27.   // Add a CSS class to both rows
  28.   ->addClass('table-row')
  29.   // Now just get the first row (at position 0)
  30.   ->eq(0)
  31.   // Add a table header in the first row
  32.   ->append('<th>This is the header</th>')
  33.   // Now go to the next row
  34.   ->next()
  35.   // Add some data to this row
  36.   ->append('<td>This is the data</td>')
  37.   // Write it all out as HTML
  38.   ->writeHTML();
  39. ?>
复制代码
详细请参考其官网及API手册(包含在源码中):http://querypath.org/
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP