首页 > PHP教程 > php开发知识文章

QueryPath,实现很多jQuery函数的PHP类库

基本使用方法

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();

?>

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。