I have raw knowledge of php, I decided to practice with parsing data from the site using phpQuery stopped at the very beginning and have been sorting out the options for quite a long time.

When you run foreach, an error occurs:

Warning: Invalid argument for foreach () in /parser.php on line 13

I read about it, but the problem did not help to solve. Tell me what you need to add, what am I doing wrong?

<?php header('Content-type: text/html; charset=utf-8'); require 'phpQuery.php'; $url='http://ria56.ru/posts/news/'; $file= file_get_contents($url); $doc = phpQuery::newDocument($file); $rianews=$doc->find('.text_posts');//извлекаем только новостные посты $links = $doc->find('.text_posts .name a')->attr('href'); foreach ($doc->find('.name a')->attr('href') as $link){ echo $link.'<br>'; } 

the library itself is connected as the link was extracted using

 $links = $doc->find('.text_posts .name a')->attr('href'); 

    2 answers 2

    You need to sort out the links from the list of found, and then take their attributes. The correct option would be something like this:

     foreach ($doc->find('.name a') as $link){ echo $link->attr('href') . '<br>'; } 
    • tried it .. Fatal error: Call to undefined method DOMElement :: attr () in /parser.php on line 12 - Evgeny Shevtsov
    • and it’s strange that he didn’t recognize it, if you just write echo $ doc-> find ('. name a') -> attr ('href'), then the first link will appear - Evgeny Shevtsov

    solved the problem, it turned out that $link was a DOMElement object, and we need phpQueryObject for this we had to do the following

     foreach ($doc->find('.name a') as $link){ $link = pq($link); echo $link->attr('href') . '<br>'; } 

    after conversions in the second line with the $link variable, you can work as with a jquery object and write something like: $link->attr('href')

    Conclusion: it was necessary to read the documentation in more detail. https://code.google.com/archive/p/phpquery/wikis/Basics.wiki