4

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 ?

Ramin Omrani
  • 3,673
  • 8
  • 34
  • 60

1 Answers1

5

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();
COil
  • 7,201
  • 2
  • 50
  • 98
  • Just tested and it works. Try getting the Crawler object instead of creating it. (new answer) – COil May 22 '17 at 15:18
  • 1
    I created a dom crawler using `array notation of strings : $string[$i]` and `substr()` and `substring` functions to achieve the goal . thanks for your time and effort – Ramin Omrani May 22 '17 at 17:17