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

标签 php symfony dom

下面的代码获取了 url、Web 内容(这里没有帮助程序,而是使用 Guzzle 的基本 cURL),使用 Dom 爬虫在页面上查找内容,例如链接或侧标记中的内容。因为爬虫函数(Crawler $node)循环通过,它是函数意味着我不能使用为新的 JsonResponse 创建的值或以任何方式在该函数之外使用值并返回 Controller 必须返回响应(给定 null)。您是否忘记在 Controller 中的某个位置添加 return 语句?

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


    }


 }

最佳答案

要访问 Closure 函数内的变量,您需要通过添加 use (&$results) 来“导入”它,请参阅下面的代码片段

$results = [];

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

return new JsonResponse($results);

对于原始类型,您需要通过在对象前面添加 & 来强制引用,只需传递变量名称就足够了

关于php - 函数(Crawler $node)symfony使用值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765104/

相关文章:

javascript - 当鼠标离开内容区域时,JS隐藏html内容

php - 当我使用以下代码 : 从目录中调用导航时,下拉导航菜单中断

php - "Call-time pass-by-reference has been removed"

php - 如何配置symfony检查:requirements?

php - 教义 2 中的多对多选择?

mysql - Doctrine - 导出mysql时首字母大写

php - 如何为 PHP 的 CLI 启用 mysqli 支持

php - 如何从 Mac 上完全卸载 symfony 和 composer

javascript - 安卓浏览器: avoid keyboard to hide when icon is pressed

javascript - (ReactJS) 函数未传递给子组件