/vendor/querypath/querypath/examples/techniques.php

  1. <?php 
  2. /** 
  3. * This file shows five different ways to iterate through the contents of a 
  4. * QueryPath. 
  5. * 
  6. * QueryPath wraps zero or more elements (or, more generally, just objects). 
  7. * Most of the operations available in QueryPath will operate on the entire  
  8. * set of objects. Sometimes, though, it is desirable to go through the results 
  9. * one at a time. These examples exhibit five ways of accomplishing this. 
  10. * 
  11. * Keep in mind that PHP passes objects (more or less) by reference, which means  
  12. * that a change to an item inside of a loop will be reflected in the main QueryPath. 
  13. * In other words, there is no need to put data back into the QueryPath if it is 
  14. * altered during a loop. 
  15. * 
  16. * @see QueryPath 
  17. *  
  18. * @author M Butcher <matt@aleph-null.tv> 
  19. * @license LGPL (The GNU Lesser GPL) or an MIT-like license. 
  20. */ 
  21.  
  22. require '../src/QueryPath/QueryPath.php'; 
  23.  
  24. $demo = '<?xml version="1.0" ?> 
  25. <data> 
  26. <li>Foo</li> 
  27. <li>Foo</li> 
  28. <li>Foo</li> 
  29. <li>Foo</li> 
  30. <li>Foo</li> 
  31. </data> 
  32. '; 
  33.  
  34. $qp = qp($demo, 'data'); 
  35.  
  36. // Iterate over elements as DOMNodes: 
  37. foreach ($qp->get() as $li_ele) { 
  38. print $li_ele->tagName . PHP_EOL; // Prints 'li' five times. 
  39.  
  40. // Iterate over elements as QueryPath objects 
  41. foreach ($qp as $li_qp) { 
  42. print $li_qp->tag() . PHP_EOL; // Prints 'li' five times 
  43.  
  44. function callbackFunction($index, $element) { 
  45. print $element->tagName . PHP_EOL; 
  46.  
  47. // Iterate using a callback function 
  48. $qp->each('callbackFunction'); 
  49.  
  50. // Iterate using a Lambda-style function 
  51. $qp->eachLambda('return $item->tagName . PHP_EOL;'); 
  52.  
  53. // Loop through by index/count 
  54. for ($i = 0; $i < $qp->size(); ++$i) { 
  55. $domElement = $qp->get($i); 
  56. print $domElement->tagName . PHP_EOL; 
.