Pergunta

I am building a $_POST query using http_build_query, but I need to transmit multiple values for one key. The problem refers to a HTML form from the United States Naval Observatory Flagstaff Station. In the section Catalogue Lists you can select multiple values to be shown.

After submitting a request you will get a overview of the search parameters. A short extract shows that multiple values refer to the same key.

...
colbits = cb_id
colbits = cb_ra
...
colbits = cb_mag
...

The thing is that I don't see a chance to transmit multiple values for the same key in PHP. If i would do it as following, the value for the key would be overwritten.

$url = 'http://www.nofs.navy.mil/cgi-bin/tfch4.test.cgi';
$data = array('colbits' => 'cb_id', 'colbits' => 'cb_ra', 'colbits' => 'cb_mag');

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

Is there any workaround for this? I already tried to send the different values as an array for the key „colbits“, but this doesn't worked as expected.

Foi útil?

Solução 2

Appending the params to the generated query string by http_build_query did the trick.

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)."&colbits=cb_id&colbits=cb_altid&colbits=cb_ra&colbits=cb_mag",
    ),
);

Outras dicas

If you want to get an array in $_POST called 'colbits':

$_POST['colbits'] == ['cb_id','cb_ra','cb_mag']

...the correct way to do it is to put a pair of square brackets after 'colbits' definition, likes this:

$data = array('colbits[]' => 'cb_id', 'colbits[]' => 'cb_ra', 'colbits[]' => 'cb_mag');

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top