Имитировать массив $ _POST через строку в PHP - PullRequest
0 голосов
/ 12 февраля 2011

Предположим, что я не могу успешно получить доступ к массиву $ _POST, но у меня есть доступность строки, в которой есть все поля со значениями там.

$string = "x_field1=Value1;x_field2=Value2;x_field3=Value3;x_field4=Value4;"

Есть ли способ перевести это в тот же формат, в котором был бы PHP $ _POST?

array { 
x_field1 => Value1
x_field2 => Value2
...
}

Чтобы имитировать точную структуру данных $_POST для передачи стороннему API для ответа? У меня есть доступ к определенным битам PHP5, поэтому я не могу использовать стандарт $_POST, у меня есть доступ только к строке с ";" в качестве разделителя для каждого переданного поля и "=" в качестве разделителя для значения поля.

Я пытался explode на ";" но это дает мне неверный результат, я тогда попытался implode массив, возвращенный для первого разнесения, а затем взорвать на =, что также не приближает меня

Ответы [ 2 ]

1 голос
/ 12 февраля 2011

parse_str() - анализирует строки запроса.

Пример со страницы документации:

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);

echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
0 голосов
/ 24 декабря 2012

Простая полезная оболочка:

class Struct implements Iterator, ArrayAccess, Countable
{
    public $items = array ();
    protected $_strict = true;

    public function __construct ($strict = true) {
        $this->_strict = $strict;
    }

    public function setStrict ($value) {
        $this->_strict = $value;
    }

    public function assign ($data) {
        if (is_array ($data))
            $this->items = @array_change_key_case ($data, CASE_LOWER);
        elseif (is_a ($data, 'Struct'))
            $this->items = $data->items;
    }

    public function append ($data) {
        if (is_array ($data))
            $this->items += @array_change_key_case ($data, CASE_LOWER);
        elseif (is_a ($data, 'Struct'))
            $this->items += $data->items;
    }

    public function merge ($data) {
        if (is_array ($data))
            $this->items = array_merge ($this->items, @array_change_key_case ($data, CASE_LOWER));
        elseif (is_a ($data, 'Struct'))
            $this->items = array_merge ($this->items, $data->items);
    }

    public function clear () {
        $this->items = array ();
    }

    public function exists ($item) {
        return isset ($this->items [strtolower ($item)]);
    }

    public function remove ($item) {
        $field = strtolower ($item);
        if (isset ($this->items [$field])) unset ($this->items [$field]);
    }

    protected function _getValue ($item) {
        $field = strtolower ($item);
        $exists = isset ($this->items [$field]);
        if ($this->_strict && !$exists) throw new OutOfBoundsException ('Struct: Field "' . $item . '" not found');
        return $exists ? $this->items [$field] : null;
    }

    public function __get ($item) {
        return $this->_getValue ($item);
    }

    public function __set ($item, $value) {
        $this->items [strtolower ($item)] = $value;
    }

    public function rewind () {
        reset ($this->items);
    }

    public function current () {
        return current ($this->items);
    }

    public function key () {
        return key ($this->items);
    }

    public function next () {
        return next ($this->items);
    }

    public function valid () {
        return $this->current () !== false;
    }

    public function offsetExists ($offset) {
        return isset ($this->items [strtolower ($offset)]);
    }

    public function offsetGet ($item) {
        return $this->_getValue ($item);
    }

    public function offsetSet ($offset, $value) {
        $this->items [strtolower ($offset)] = $value;
    }

    public function offsetUnset ($offset) {
        $field = strtolower ($ofset);
        if (isset ($this->items [$field])) unset ($this->items [$field]);
    }

    public function count () {
        return count ($this->items);
    }

    public function get ($item, $default = null) {
        return $this->exists ($item) ? $this->$item : $default;
    }
}

// Use it as POST wrapper
$post = new Struct ($_POST);
var_dump ($post->var1);

// Or just any other array
parse_str ('first=value&arr[]=foo+bar&arr[]=baz', $output);
$myPost = new Struct ($output);
var_dump ($myPost->first);
try
{
    var_dump ($myPost->nonexistent_field);
}
catch (OutOfBoundsException $e)
{
    echo "Exception catched! " . $e->getMessage ();
}
$myPost->setStrict (false);
var_dump ($myPost->nonexistent_field);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...