4

目的是form[id=thisAwesomeRemoteForm][action=#]在远程网站上填充 a。只有一个字段 ( input[name=awesomeField]) 需要填充,然后需要提交表单。作为最终要求,用户需要从我的网站重定向到这个远程网站,就好像它已经在远程网站上提交了表单一样。

长话短说,我需要用户能够点击我的链接,让 PHP 完成这项工作并被重定向到这个远程网站,就好像它已经填写并提交了远程网站上的表单一样。我不必让用户自己填写远程表单。

到目前为止的代码是:

use Goutte\Client;
// ...
public function gotoAction($data)
{
    $client = new Client();
    $crawler = $client->request('GET', self::MY_URL);

    $form = $crawler->filter('form[id=thisAwesomeRemoteForm]')->form();

    $form->setValues(array('awesomeField' => $data));
    $crawler = $client->submit($form);

    return $this->redirect($form->getUri());
}

到目前为止,我被重定向到第一个 URL 所在的form位置,而不是form应该指向的位置。但是,该字段填充了正确的数据。

我的代码是否正确以实现我的目的(因此,它是可能使用 JavaScript 发送表单或其他内容的远程网站)还是我遗漏了一些相当明显的东西?

4

1 回答 1

1

Goutte 基本上是 Guzzle 到Symfony\BrowserkitAPI 的适配器。基于粗略分析的源代码Goutte\Client没有effectiveUrl()使用或结转。这意味着如果发生重定向,您将不会“捡起它”。

您可以使用以下代码片段使用基本组件(Guzzle、DomCrawler)轻松地执行相同的功能:

$client = new GuzzleHttp\Client([
    'debug' => true, // only to troubleshoot
);

// Obtain the html page with the form
$request = $client->createRequest('GET', $url);
$response = $client->send($request);
// or $response = $client->get($url);

// create crawler and obtain the form.
$crawler = new Symfony\Component\DomCrawler\Crawler(null, $response->getEffectiveUrl());
$crawler->addContent(
    $response->getBody()->__toString(),
    $response->getHeader('Content-Type')
);

$form = $crawler->form('form_identifier');
$form->setValues($data_array);

//form submission
$request = $client->createRequest(
    $form->getMethod(),
    $form->getUrl(),
    [
        'body' => $form->getPhpValues(),
]);

$response = $client->send($request);
于 2015-04-30T14:25:44.970 回答