使用值的函数(Crawler $ node)symfony问题

时间:2016-11-23 12:53:15

标签: php symfony dom

以下代码获取网址,网页内容(帮助程序不在此处,但基本cURL与Guzzle)使用Dom爬虫在页面上查找内容,如链接或侧标记中的内容。因为循环函数(Crawler $ node)循环,它是函数意味着我不能使用为新JsonResponse创建的值或者在该函数之外的任何方式返回                控制器必须返回响应(给定null)。您是否忘记在控制器中的某处添加返回语句?

  namespace AppBundle\Controller;

 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\DomCrawler\Crawler;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\HttpFoundation\JsonResponse;


class DefaultController extends Controller
{

public $use;
public $item;
public $price;
public $link;
public $code;

/**
 * @Route("/", name="homepage")
 */

public function indexAction()
{


    $html = $this->container->get('webscraper.helper')->contents('url');

    $crawler = new Crawler($html['html']);

    $crawler->filter('div.product')->each(function (Crawler $node) {

            $item =  $node->filter('h3')->text(); 

            $price =  $node->filter('p')->text(); 

            $link = $node->filterXPath("//a/@href")->text();

                    $secondpage = $this->container->get('webscraper.helper')->contents($link);

                   // echo $secondpage['size'];

                    $crawler2 = new Crawler($secondpage['html']);

                    $description = $crawler2->filterXPath("//div[@class='productText']")->text();
    //   echo $size;


            $use[] = array('title' => $item,'size' =>'5' ,'unit_price' => $price,'description' => $description);


           });
   // because of above }); cannot access $use 
    return new JsonResponse($use);


    }


 }

1 个答案:

答案 0 :(得分:2)

要访问Closure功能中的变量,您需要" import"通过添加use (&$results),请参阅下面的我的代码段

$results = [];

$crawler->filter(self::RESULT_SELECTOR)->each(function (Crawler $node) use (&$results) {
    // code here
}

return new JsonResponse($results);

对于原始类型,您需要通过在&前加上足以传递变量名称的对象来强制引用