stringhe di query di decodifica in PHP
-
16-09-2019 - |
Domanda
Va bene, così ho scritto un'implementazione API REST utilizzando mod_rewrite e PHP. Sono accettare una stringa di interrogazione tramite il corpo di HTTP DELETE richieste (... gemito collettivo?). Argomenti sulla saggezza di entrambe le precedenti dichiarazioni a parte, quello che ho trovato è che PHP non analizza automaticamente il corpo della richiesta di richieste DELETE (vale a dire $ _POST è vuoto nonostante query string forma codificata appare nel corpo della richiesta). Questo non mi sorprende particolarmente. Quello che ho trovato sorprendente è che io sono stato in grado di trovare una funzione PHP built-in per l'analisi di una stringa di query ?? Ho semplicemente trascurato qualcosa? Posso fare qualcosa di simile:
public function parseQS($queryString, &$postArray){
$queryArray = explode('&', $queryString);
for($i = 0; $i < count($queryArray); $i++) {
$thisElement = split('=', $queryArray[$i]);
$postArray[$thisElement[0]] = htmlspecialchars(urldecode($thisElement[1]));
}
}
... sembra proprio strano che non ci sarebbe stato un PHP built-in per gestire questa situazione. Inoltre, sospetto non dovrebbe usare htmlspecialcharacters & urldecode a valori di modulo codifica scrub ... è un diverso tipo di codifica, ma sto avendo anche esigente problemi che PHP funzione dovrei usare per decodificare i dati codificati forma .
Tutti i suggerimenti saranno apprezzati.
Soluzione
parse_str . Bad nome, ma fa quello che vuoi. E notate che restituisce nulla, il secondo argomento viene passato per riferimento.
Altri suggerimenti
C'è una funzione che lo fa - http://php.net/parse_str . Dal momento che PHP ha a che fare questo per sé, non c'è motivo di non aprire anche per l'utilizzo nella API.
analizza la stringa in variabili vuoto parse_str (string $ str [, un array & $ arr])
analizza str come se fosse la query stringa passata tramite un URL e set variabili nell'ambito corrente.
<?php
$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
parse_str href="http://codepad.org/s4w6DSh9" rel="nofollow"> schifo .
parse_str
va bene per le cose semplici, ma non è la stessa di modo integrato di PHP di creare la variabile magia $_GET
. Perché?!? Non ne ho idea. Ho sviluppato la mia versione che credo corrisponda parsing PHP esattamente (fatemi sapere se è possibile trovare tutti gli esempi che dimostrano il contrario).
function betterParseStr( $string )
{
return array_reduce( explode( "&", $string ), function( $array, $string_piece ) {
if( $string_piece === "" ) return $array;
$equal_offset = strpos( $string_piece, "=" );
if( $equal_offset === FALSE ) {
$key = urldecode( $string_piece );
$value = "";
} else {
$key = urldecode( substr( $string_piece, 0, $equal_offset ) );
$value = urldecode( substr( $string_piece, $equal_offset + 1 ) );
}
if( preg_match( "/^([^\[]*)\[([^\]]*)](.*)$/", $key, $matches ) ) {
$key_path = array( $matches[1], $matches[2] );
$rest = $matches[3];
while( preg_match( "/^\[([^\]]*)](.*)$/", $rest, $matches ) ) {
$key_path[] = $matches[1];
$rest = $matches[2];
}
} else {
//replace first [ for _
//why?!? idk ask PHP it does
//Example: ?key[[=value -> array( "key_[" => "value" )
$key_path = array( preg_replace('/\[/', '_', $key, 1 ) );
}
if( strlen( $key_path[0] ) > 0 && substr( $key_path[0], 0, 1 ) !== "[" ) {
$current_node = &$array;
$last_key = array_pop( $key_path );
$resolve_key = function( $key, array $array ) {
if( $key === "" || $key === " " ) {
$int_array = array_filter( array_keys( $array ), function( $key ) { return is_int( $key ); } );
$key = $int_array ? max( $int_array ) + 1 : 0;
}
return $key;
};
foreach( $key_path as $key_path_piece ) {
$key_path_piece = $resolve_key( $key_path_piece, $current_node );
if( ! array_key_exists( $key_path_piece, $current_node ) || ! is_array( $current_node[$key_path_piece] ) ) {
$current_node[$key_path_piece] = array();
}
$current_node = &$current_node[$key_path_piece];
}
$current_node[$resolve_key( $last_key, $current_node )] = $value;
}
return $array;
}, array() );
}
È possibile utilizzare il parse_str
funzione :
parse_str($queryString, $args);
http://us2.php.net/manual/en /function.parse-url.php
parse_url vi aiuterà si afferra la porzione di DOCUMENT_URI che contiene la query effettiva.
Si può quindi passare quella sezione off per parse_str per estrarre singoli elementi della query.
Ho costruito una semplice libreria per analizzare stringa di query per filtrare, ordinare e selezionare i campi per il mio API REST. una versione ingenua di odata. la stringa di query trasformato in oggetto e o array di oggetti. per esempio:
filtri:
www.example.com/resource?@filters=filedName operator 'the value'
disponibili operatori eq, ne, gt, lt, come, iLike, le, ge
$filtersResult = $parser->filters();
$filtersResult[0]->field // name
$filtersResult[0]->operator // eq
$filtersResult[0]->getOperator() // "="
$filtersResult[0]->value // 'what ever'
per ordinare:
//name is asc , surname desc
@orderby=name,-surname
$sorts = $parser->orderBy() // you can set defaults if u want
$sorts[0]->filed //name
$sorts[0]->direction //asc
$sorts[1]->filed //surname
$sorts[1]->direction //desc
per embed:
@embed=resourceOne(@fields=name,code)(@filters=nameembed eq 'what ever'),mobiles(@orderby=sortFieldOne)
$embedResult = $parser->embed(); //return array of embed each
//object contains filters , sort , fields | empty array
$embedResult[0]->resource // resourceOne
$embedResult[0]->fields // array of fields [name,code]
$embedResult[0]->filters // array of filters or empty array
$embedResult[1]->resource // mobiles
$embedResult[1]->orderBy // array of order by objects
public function parseQS($queryString, &$postArray){
parse_str($queryString, $postArray);
}
; -)