Search code examples
phpparsingpostforeach

How can I extract variables from a string from POST?


first time here with question but Im stuck and can't figure this out. Any help is appreciated.

I am sending a string that is delimited with "###" as a "payload". I want to parse the string to array to get individual strings of data. I then want to loop through the individual string to extract the variables so I can input in my database. Im not sure the best way to go about it, I've been testing different methods and either get and empty string response or status 500 code.

Here is example "payload" string I send from POST:

key=03968db0386af63d57f48e8cbfd16971&name=LE%252520Tropical%252520Tuffet%252520%25252D%252520Luau&type=Pot%2520with%2520Plant###key=239fa7207c241d8a55743d9988839055&name=Modern%252520Oasis%252520Philodendron%252520Pot%252520%25252D%252520Pink%252520Swirls&type=Pot%2520with%2520Plant
<?php
$payload = $_POST['payload'];
$records = implode("\n", $payload);
foreach($records as $record){
    list($key,$name,$type) = explode("###", $record);
    echo $key;
}
?>

I'm expecting to receive payload from POST, parse to individual strings for each record using the "###" delimiter, extract the key, name, and type from the individual strings so I can add to my data base with mysqli. So each entry in the database will have a key identifier as primary and the stats of each key.

Thank You


Solution

  • It looks like you should be using ### to create an array of query strings. Then you can use parse_str() to parse each of the name=value parameters into variables.

    $payload = $_POST['payload'];
    $records = explode('###', $payload);
    foreach ($records as $record) {
        parse_str($record, $vars);
        ['key' => $key, 'name' => $name, 'type' => $type] = $vars;
        echo $key;
    }