0

I have a comma separated list of numbers from a post variable, which outputs e.g:

123, 456, 789, 101, 112 // Number comma space

I then use the following code to process these IDs individually:

$id_string = $_POST['ids'];


$id_array = array_map('trim', explode(',', $id_string));

    foreach ($id_array as $value){
        $url = 'http://myserver.com';
        $data = array('a' => $value, 'reStock' => 'true');
        $get = array();

            foreach($data as $k => $v){
            $get[] = $k . '=' . urlencode($v);
            }

            $get = implode('&', $get);

            $opts = array('http' =>
            array(
            'method'  => 'GET',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $get
            )
            );

        $context = stream_context_create($opts);
        $mxsendstock = file_get_contents($url, false, $context);
    }

After testing all afternoon, I can't get the foreach to work - nothing happens. The only possible cause I can see is if I'm handling the comma-separated list correctly.

Any ideas?

9
  • 2
    You might consider taking a look at the http_build_str() function Commented Jun 29, 2013 at 12:56
  • Thanks, that looks like it'll be very handy for me :) In terms of the actual process, the function seems to work without issue when using a real array, i.e. $ids = 123,456,789; So I'm trying to find out if I'm converting my string to an array properly. Thanks, J Commented Jun 29, 2013 at 12:58
  • 1
    "I can't get the foreach to work" is not helpful. People will need to spend time discovering how it does not work, which you already know. Please do tell. Commented Jun 29, 2013 at 12:58
  • Thanks for your comment @Jon, as per the original post, how it doesn't work is: nothing happens. At all. Not a single Get request. Nothing. Thanks, J Commented Jun 29, 2013 at 13:00
  • 1
    A simple var_dump() of $id_array immediately before the foreach() should tell you if you're converting it to an array correctly Commented Jun 29, 2013 at 13:00

1 Answer 1

1

is there any problem using that like this?

<?php
  $id_string  = $_POST['ids'];
  $id_array   = array_map( 'trim', explode( ',', $id_string ) );

  foreach( $id_array as $value ) {
    $url  = 'http://myserver.com/';
    $data = array( 'a' => $value, 'reStock' => 'true' );
    $get  = http_build_query( $data );

    $mxsendstock  = file_get_contents( $url."?".$get );
    print( htmlspecialchars( $mxsendstock ) );
  }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

That's terrific, it works perfectly. Thank you very much for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.