Search code examples
phpphpquery

How do I generate an array of the items from a list (ul) tag?


From the following code:

<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

How do I create an array using phpQuery

array(
  'Coffee',
  'Tea',
  'Milk'
);

Here's my first attempt, it is very ugly

    $doc = phpQuery::newDocumentHTML(...);
    $img = $doc->find('ol');
    $list = array();
    function attrsrc($i, $v){
        global $list;
        $list[] =  phpQuery::pq($v)->text();
    }
    phpQuery::each($img, 'attrsrc',  new CallbackParam, new CallbackParam);
    print_r($list);

Solution

  • Try this:

    include 'phpQuery.php';
    
    $string = '<ol> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol>';
    $content = phpQuery::newDocument($string)->find('ol li');
    
    $drinks = array();
    
    foreach ($content as $li) {
         $drinks[] = pq($li)->text();
    }
    
    print_r($drinks);