Ramin Omrani
Ramin Omrani

Reputation: 3761

Can not fetch value of an element using Symfony Dom Crawler

I am fetching a URL using guzzle POST method . its working and returning the page that I want . but the problem is when I want to get the value of an input element in a form in that page, the crawler returns nothing . I don't know why .

PHP:

<?php
use Symfony\Component\DomCrawler\Crawler;
use Guzzle\Http\Client;

$client = new Client();

$request = $client->get("https://example.com");
$response = $request->send();
$getRequest = $response->getBody();
$cookie = $response->getHeader("Set-Cookie");


$request = $client->post('https://example.com/page_example.php', array(
    'Content-Type' => 'application/x-www-form-urlencoded',
    'Cookie' => $cookie
    ), array(
        'param1' => 5,
        'param2' => 10,
        'param3' => 20
    ));

$response = $request->send();
$pageHTML = $response->getBody();

//fetch orderID
$crawler = new Crawler($pageHTML);
$orderID = $crawler->filter("input[name=orderId]")->attr('value');//there is only one element with this name

echo $orderID; //returns nothing

What should I do ?

Upvotes: 4

Views: 2242

Answers (1)

COil
COil

Reputation: 7596

You don't have to create a Crawler:

$crawler = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
    'param1' => 5,
    'param2' => 10,
    'param3' => 20
)); 
$orderID = $crawler->filter("input[name=orderId]")->attr('value');

This assumes your POST isn't being redirected, if it is redirected you should add before calling the filter function:

$this->assertTrue($client->getResponse()->isRedirect());
$crawler = $client->followRedirect();

Upvotes: 5

Related Questions