Php вывести массив post

Содержание
  1. Метод post php пример пост запроса
  2. Подробно о методе post в php
  3. Что такое метод POST?
  4. Как обозначается метод отправки данных «POST» в форме?
  5. Место обработки данных из метода POST?
  6. Что нужно, чтобы отправить POST запрос!?
  7. Алгоритм отправки POST запроса!?
  8. Какие данные отправляет метод POST
  9. Какой тип данных у POST?
  10. Массив POST — что это?
  11. Получение массива POST с примером.
  12. Соберем весь код для получения и вывода массива POST
  13. Форма для отправки массива POST
  14. Форма с методом POST
  15. Как получать данные отправленные методом POST
  16. Живой пример отправки данных методом POST
  17. Как отправить POST запрос на другую страницу!?
  18. Как работает отправка post запроса на другую страницу!?
  19. Код страницы для приема post запроса
  20. $_POST
  21. Описание
  22. Примеры
  23. Примечания
  24. Смотрите также
  25. User Contributed Notes 7 notes
  26. Вывод значений из массива $_POST
  27. print_r
  28. Описание
  29. Список параметров
  30. Возвращаемые значения
  31. Примеры
  32. Примечания
  33. Смотрите также
  34. User Contributed Notes 36 notes

Метод post php пример пост запроса

Подробно о методе post в php

Что такое метод POST?

Как обозначается метод отправки данных «POST» в форме?

Место обработки данных из метода POST?

Место(условно) где будет происходить обработка только два:

Данные будут обработаны:

Либо на этой странице.

Что нужно, чтобы отправить POST запрос!?

Для того, чтобы отправить post запрос потребуется:

Форма, из которой будет отправляться «post запрос».

Скрипт, который получит, обработает и выведет результат(если это требуется.)

Алгоритм отправки POST запроса!?

Алгоритм отправки данных методом post :

Обрабатываем данные отправление методом пост.

Какие данные отправляет метод POST

На живом примере(следующий пункт) разберем, как передаются данные в методом «POST».

Какой тип данных у POST?

Зачем нужно знать, какое тип у данных в методе POST?

Если вы знаете тип данных, то у соответствующих типах есть свои признаки поведения!

Если мы знаем поведение, то можем управлять этими данными.

Тип данных, которые передает метод POST — это массив!

Массив POST — что это?

Пока — вы ничего не отправили методом POST, то в нем ничего нет. Для этого, выведем через var_dump($_POST);

Ниже рассматривается пример отправки методом post и получаем результат. и там же выводим массив «$_POST».

После нажатия на кнопку, вы можете вернуться сюда, и посмотреть, что вернет функция var_dump.

Получение массива POST с примером.

Для этого нам понадобится:

Форма из которой будем отправлять данные. Подробно на форме остановимся ниже.

Чтобы приять данные нужно создать такую запись в php, для вывода массива используем print_r:

Если вы размещаете такую запись внутри html документа, нужно, чтобы html понимал php

Соберем весь код для получения и вывода массива POST

Форма для отправки массива POST

У вас есть два варианта:

Просто нажмите на кнопку отправить и вы получите результат «массива POST».

Либо в полях ввода напишите свою информацию.

И нажимаем отправить!

Форма с методом POST

Разберем подробно из чего должна состоять форма для отправки «запроса POST».

Форма состоит из:

Необходимый атрибут method, который будет указывать тип метода, в нашем случае это «POST».

Атрибут action можем ставить, можем оставить просто пустым — будем обрабатывать запрос post на этой странице!

Форму выведем ниже!

Далее нам нужно переданные данные из этой формы обработать!

Как получать данные отправленные методом POST

Приступим к обработке переданных данных, нам нужно условие, по которому будем проверять, отправлен ли «post запрос» — это условие if, после него пишем двойные круглые скобки » () » и помещаем туда название атрибута «name из формы» — рассмотрим это на одном из полей input:

Для данного поля условие получения данных будет таким:

После круглых скобок ставим фигурные » <> » и внутри них, ну, давайте, передадим полученные данные в переменную $login + не забываем про безопасность strip_tags:

Полностью можем собрать получение пост запроса из этого input-a :

Тоже самое делаем со вторым полем ввода:

Мы рассмотрели два поля ввода!

Но ведь у нас есть кнопка отправить!

Для данной кнопки можно составить тоже условие и уже внутрь поместить два условия о которых мы сказали выше.

Это будет проверка на отправку данных, т.е. была ли нажата кнопка submit:

Живой пример отправки данных методом POST

Не будем повторять, что уже было сказано, лишь посмотрим на некоторые изменения, которые я внес в форму, чтобы она работала так, как мне нужно здесь.

Чтобы вы не ходили в поисках результата, нам потребуется вернуться к нашему результату в этом пункте, поэтому нам понадобится якорь

И для вывода переданных данных используем echo, использовали два типа кавычек ‘ и «

Вы ввели данные:

$login = ‘. strip_tags ( $_POST[‘login’] ).’

$psw = ‘. strip_tags ( $_POST[‘psw’] ).’

Полный код выше идущей формы с php обработчиком пост запроса!

Вы ввели данные:

$login = ‘. strip_tags ( $_POST[‘login’] ).’

$psw = ‘. strip_tags ( $_POST[‘psw’] ).’

Введите какие-то данные в поля ввода и нажмите отправить:

Как отправить POST запрос на другую страницу!?

Первое! Откройте страницу и посмотрите, что там написано!

Теперь наберите текст и отправьте данные. методом post? на другую страницу:

Как работает отправка post запроса на другую страницу!?

Нам понадобится опять форма для отправки каких-то данных:

+ использовали тип hidden(скрытое поле), в котором отправляем ссылку(прост пример. )

В указываем страницу. на которую будем отправлять pos запрос!

Код страницы для приема post запроса

На странице для приема данных переданных через post делаем все абсолютно аналогично, что и выше было рассказано! Создаем условия и проверяем были ли переданы данные методом post!

Пример страницы для приема пост запроса

Вы отправили данные:

$send_var = ‘. strip_tags ( $_POST[‘send_var’] ).’

$url = ‘. strip_tags ( $_POST[‘url’] ).’

Post запрос был отправлен со страницы’;

echo ‘Вы здесь ничего не увидите, пока не отправить пост запрос со страницы со страницы’;

Источник

$_POST

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_POST — Переменные HTTP POST

Описание

Ассоциативный массив данных, переданных скрипту через HTTP методом POST при использовании application/x-www-form-urlencoded или multipart/form-data в заголовке Content-Type запроса HTTP.

Примеры

Пример #1 Пример использования $_POST

Подразумевается, что пользователь отправил через POST name=Иван

Результатом выполнения данного примера будет что-то подобное:

Примечания

Это ‘суперглобальная’ или автоматическая глобальная переменная. Это просто означает, что она доступна во всех контекстах скрипта. Нет необходимости выполнять global $variable; для доступа к ней внутри метода или функции.

Смотрите также

User Contributed Notes 7 notes

One feature of PHP’s processing of POST and GET variables is that it automatically decodes indexed form variable names.

I’ve seem innumerable projects that jump through extra & un-needed processing hoops to decode variables when PHP does it all for you:

Example pseudo code:

Many web sites do this:

When they could do this:

With the first example you’d have to do string parsing / regexes to get the correct values out so they can be married with other data in your app. whereas with the second example.. you will end up with something like:
( $_POST [ ‘person’ ]);
//will get you something like:
array (
0 => array( ‘first_name’ => ‘john’ , ‘last_name’ => ‘smith’ ),
1 => array( ‘first_name’ => ‘jane’ , ‘last_name’ => ‘jones’ ),
)
?>

This is invaluable when you want to link various posted form data to other hashes on the server side, when you need to store posted data in separate «compartment» arrays or when you want to link your POSTed data into different record handlers in various Frameworks.

Remember also that using [] as in index will cause a sequential numeric array to be created once the data is posted, so sometimes it’s better to define your indexes explicitly.

If you want to receive application/json post data in your script you can not use $_POST. $_POST does only handle form data.
Read from php://input instead. You can use fopen or file_get_contents.

// Get the JSON contents
$json = file_get_contents ( ‘php://input’ );

// decode the json data
$data = json_decode ( $json );
?>

I know it’s a pretty basic thing but I had issues trying to access the $_POST variable on a form submission from my HTML page. It took me ages to work out and I couldn’t find the help I needed in google. Hence this post.

Make sure your input items have the NAME attribute. The id attribute is not enough! The name attribute on your input controls is what $_POST uses to index the data and therefore show the results.

Note that $_POST is NOT set for all HTTP POST operations, but only for specific types of POST operations. I have not been able to find documentation, but here’s what I’ve found so far.

$_POST _is_ set for:

In other words, for standard web forms.

$_POST is NOT set for:

A type used for a generic HTTP POST operation.

For a page with multiple forms here is one way of processing the different POST values that you may receive. This code is good for when you have distinct forms on a page. Adding another form only requires an extra entry in the array and switch statements.

if (!empty( $_POST ))
<
// Array of post values for each different form on your page.
$postNameArr = array( ‘F1_Submit’ , ‘F2_Submit’ , ‘F3_Submit’ );

// Find all of the post identifiers within $_POST
$postIdentifierArr = array();

foreach ( $postNameArr as $postName )
<
if ( array_key_exists ( $postName , $_POST ))
<
$postIdentifierArr [] = $postName ;
>
>

// Only one form should be submitted at a time so we should have one
// post identifier. The die statements here are pretty harsh you may consider
// a warning rather than this.
if ( count ( $postIdentifierArr ) != 1 )
<
count ( $postIdentifierArr ) 1 or
die( «\$_POST contained more than one post identifier: » .
implode ( » » , $postIdentifierArr ));

// We have not died yet so we must have less than one.
die( «\$_POST did not contain a known post identifier.» );
>

switch ( $postIdentifierArr [ 0 ])
<
case ‘F1_Submit’ :
echo «Perform actual code for F1_Submit.» ;
break;

case ‘Modify’ :
echo «Perform actual code for F2_Submit.» ;
break;

case ‘Delete’ :
echo «Perform actual code for F3_Submit.» ;
break;
>
>
else // $_POST is empty.
<
echo «Perform code for page without POST data. » ;
>
?>

Источник

Вывод значений из массива $_POST

Имеется форма значения передаются постом.

Мне нужно вывести значения из массива ПОСТ как только они придут.
вместо %s подставляются варианты ответов.
Я же не могу узнать что мне придет в пост a1 или a2.
Так вот как же мне вывести то что придет в массив пост

Добавлено через 24 минуты
сори, решил вопрос.
Просто в поле name дал одинаковое значение.

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Вывод значений массива сортируя блоки по первым буквам значений
Привет всем! Читаю заголовок своей темы и поражаюсь своей фантазией )) Проблема вот в чем: есть.

Запись значений в массив через $_POST
Пожалуйста помогите не могу сделать: С клавиатуры вводятся n чисел. Составьте программу.

Вывод текста с $_POST с лишними символами
Здравствуйте! есть селект .

И какой тогда, по вашему input будет выхватывать скрипт?
Делайте имена уникальными.

открою вам код, может так будет понятнее.

Передается у меня то что находится в %s А подставляется из $myrow.
На данный момент все работает так как надо.
Но не могу сделать 1 вещь.

У меня перед проверкой выводится что ответ дан не верно. Хотя запрос я не посылал через кнопку.
Пытался оградиться такой конструкцией, что бы не выводился результат пока не нажал на кнопку. Но получается что запрос POST посылается где то до выбора ответа. Но никак не нахожу где

Источник

(PHP 4, PHP 5, PHP 7, PHP 8)

print_r — Выводит удобочитаемую информацию о переменной

Описание

print_r() выводит информацию о переменной в удобочитаемом виде.

print_r() , var_dump() и var_export() могут также показывать защищённые и закрытые атрибуты объектов. Статические элементы класса не будут отображены.

Список параметров

Выражение для вывода на экран.

Если вы хотите перехватить вывод print_r() , используйте параметр return . Если его значение равно true , то print_r() вернёт информацию вместо вывода в браузер.

Возвращаемые значения

Если в функцию передаются значения типов string , int или float , будет напечатано само значение. Если передаётся массив array , значения будут напечатаны в формате, показывающем ключи и элементы массива. Аналогичный формат вывода используется для объектов.

Если параметр return установлен в true , данная функция вернёт строку ( string ). В противном случае возвращаемое значение будет равно true .

Примеры

Пример #1 Пример использования print_r()

Результат выполнения данного примера:

Пример #2 Пример использования параметра return

Примечания

Когда используется параметр return , функция использует внутреннюю буферизацию вывода до PHP 7.1.0, поэтому её нельзя использовать внутри callback-функции ob_start() .

Смотрите также

  • ob_start() — Включение буферизации вывода
  • var_dump() — Выводит информацию о переменной
  • var_export() — Выводит или возвращает интерпретируемое строковое представление переменной

User Contributed Notes 36 notes

I add this function to the global scope on just about every project I do, it makes reading the output of print_r() in a browser infinitely easier.

function print_r2 ( $val ) <
echo » ;
>
?>

It also makes sense in some cases to add an if statement to only display the output in certain scenarios, such as:

I’ve fixed function wrote by Matt to reverse print_r — it had problems with null values. Created a GIST for that too so please add any future fixes in there instead of this comment section:
https://gist.github.com/simivar/037b13a9bbd53ae5a092d8f6d9828bc3

return $input ;
> else <
// this is an array or object, lets parse it
$match = array();
if ( preg_match ( «/(\s<5,>)\(/» , $lines [ 1 ], $match )) <
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match [ 1 ];
$spaces_length = strlen ( $spaces );
$lines_total = count ( $lines );
for ( $i = 0 ; $i $lines_total ; $i ++) <
if ( substr ( $lines [ $i ], 0 , $spaces_length ) == $spaces ) <
$lines [ $i ] = substr ( $lines [ $i ], $spaces_length );
>
>
>
$is_object = trim ( $lines [ 0 ]) == ‘stdClass Object’ ;
array_shift ( $lines ); // Array
array_shift ( $lines ); // (
array_pop ( $lines ); // )
$input = implode ( «\n» , $lines );
$matches = array();
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all ( «/^\s<4>\[(.+?)\] \=\> /m» , $input , $matches , PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
$pos = array();
$previous_key = » ;
$in_length = strlen ( $input );
// store the following in $pos:
// array with key = key of the parsed array’s item
// value = array(start position in $in, $end position in $in)
foreach ( $matches as $match ) <
$key = $match [ 1 ][ 0 ];
$start = $match [ 0 ][ 1 ] + strlen ( $match [ 0 ][ 0 ]);
$pos [ $key ] = array( $start , $in_length );
if ( $previous_key != » ) <
$pos [ $previous_key ][ 1 ] = $match [ 0 ][ 1 ] — 1 ;
>
$previous_key = $key ;
>
$ret = array();
foreach ( $pos as $key => $where ) <
// recursively see if the parsed out value is an array too
$ret [ $key ] = print_r_reverse ( substr ( $input , $where [ 0 ], $where [ 1 ] — $where [ 0 ]));
>

return $is_object ? (object) $ret : $ret ;
>
>
?>

Here is another version that parses the print_r() output. I tried the one posted, but I had difficulties with it. I believe it has a problem with nested arrays. This handles nested arrays without issue as far as I can tell.

function print_r_reverse ( $in ) <
$lines = explode ( «\n» , trim ( $in ));
if ( trim ( $lines [ 0 ]) != ‘Array’ ) <
// bottomed out to something that isn’t an array
return $in ;
> else <
// this is an array, lets parse it
if ( preg_match ( «/(\s<5,>)\(/» , $lines [ 1 ], $match )) <
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match [ 1 ];
$spaces_length = strlen ( $spaces );
$lines_total = count ( $lines );
for ( $i = 0 ; $i $lines_total ; $i ++) <
if ( substr ( $lines [ $i ], 0 , $spaces_length ) == $spaces ) <
$lines [ $i ] = substr ( $lines [ $i ], $spaces_length );
>
>
>
array_shift ( $lines ); // Array
array_shift ( $lines ); // (
array_pop ( $lines ); // )
$in = implode ( «\n» , $lines );
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all ( «/^\s<4>\[(.+?)\] \=\> /m» , $in , $matches , PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
$pos = array();
$previous_key = » ;
$in_length = strlen ( $in );
// store the following in $pos:
// array with key = key of the parsed array’s item
// value = array(start position in $in, $end position in $in)
foreach ( $matches as $match ) <
$key = $match [ 1 ][ 0 ];
$start = $match [ 0 ][ 1 ] + strlen ( $match [ 0 ][ 0 ]);
$pos [ $key ] = array( $start , $in_length );
if ( $previous_key != » ) $pos [ $previous_key ][ 1 ] = $match [ 0 ][ 1 ] — 1 ;
$previous_key = $key ;
>
$ret = array();
foreach ( $pos as $key => $where ) <
// recursively see if the parsed out value is an array too
$ret [ $key ] = print_r_reverse ( substr ( $in , $where [ 0 ], $where [ 1 ] — $where [ 0 ]));
>
return $ret ;
>
>

I always use this function in my code, because most of my functions return an Array or Boolean :

function printr ( $object , $name = » ) <

if ( is_array ( $object ) ) <
print ( » ) ;
> else <
var_dump ( $object ) ;
>

?>

( print_r gives no output on FALSE and that can be annoying! )

This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky. ):

/**
* An alternative to print_r that unlike the original does not use output buffering with
* the return parameter set to true. Thus, Fatal errors that would be the result of print_r
* in return-mode within ob handlers can be avoided.
*
* Comes with an extra parameter to be able to generate html code. If you need a
* human readable DHTML-based print_r alternative, see http://krumo.sourceforge.net/
*
* Support for printing of objects as well as the $return parameter functionality
* added by Fredrik Wollsén (fredrik dot motin at gmail), to make it work as a drop-in
* replacement for print_r (Except for that this function does not output
* paranthesises around element groups. 😉 )
*
* Based on return_array() By Matthew Ruivo (mruivo at gmail)
* (http://se2.php.net/manual/en/function.print-r.php#73436)
*/
function obsafe_print_r ( $var , $return = false , $html = false , $level = 0 ) <
$spaces = «» ;
$space = $html ? » » : » » ;
$newline = $html ? «
» : «\n» ;
for ( $i = 1 ; $i 6 ; $i ++) <
$spaces .= $space ;
>
$tabs = $spaces ;
for ( $i = 1 ; $i $level ; $i ++) <
$tabs .= $spaces ;
>
if ( is_array ( $var )) <
$title = «Array» ;
> elseif ( is_object ( $var )) <
$title = get_class ( $var ). » Object» ;
>
$output = $title . $newline . $newline ;
foreach( $var as $key => $value ) <
if ( is_array ( $value ) || is_object ( $value )) <
$level ++;
$value = obsafe_print_r ( $value , true , $html , $level );
$level —;
>
$output .= $tabs . «[» . $key . «] => » . $value . $newline ;
>
if ( $return ) return $output ;
else echo $output ;
>
?>

Built on a function earlier posted in these comments as stated in the Doc comment. Cheers! /Fredrik (Motin)

The following will output an array in a PHP parsable format:

if( count ( $items ) > 0 )
<
echo $root . ‘ = array(‘ ;

Here is a print_r that produces xml:
(now you can expand/collapse the nodes in your browser)

( ‘Content-Type: text/xml; charset=UTF-8’ );
echo print_r_xml ( $some_var );

function print_r_xml ( $arr , $first = true ) <
$output = «» ;
if ( $first ) $output .= » \n \n» ;
foreach( $arr as $key => $val ) <
if ( is_numeric ( $key )) $key = «arr_» . $key ; // switch ( gettype ( $val )) <
case «array» :
$output .= » . htmlspecialchars ( $key ). » type=’array’ size='» . count ( $val ). «‘>» .
print_r_xml ( $val , false ). » . htmlspecialchars ( $key ). «>\n» ; break;
case «boolean» :
$output .= » . htmlspecialchars ( $key ). » type=’bool’>» .( $val ? «true» : «false» ).
» . htmlspecialchars ( $key ). «>\n» ; break;
case «integer» :
$output .= » . htmlspecialchars ( $key ). » type=’integer’>» .
htmlspecialchars ( $val ). » . htmlspecialchars ( $key ). «>\n» ; break;
case «double» :
$output .= » . htmlspecialchars ( $key ). » type=’double’>» .
htmlspecialchars ( $val ). » . htmlspecialchars ( $key ). «>\n» ; break;
case «string» :
$output .= » . htmlspecialchars ( $key ). » type=’string’ size='» . strlen ( $val ). «‘>» .
htmlspecialchars ( $val ). » . htmlspecialchars ( $key ). «>\n» ; break;
default:
$output .= » . htmlspecialchars ( $key ). » type=’unknown’>» . gettype ( $val ).
» . htmlspecialchars ( $key ). «>\n» ; break;
>
>
if ( $first ) $output .= » \n» ;
return $output ;
>

Here is a function that formats the output of print_r as a expandable/collapsable tree list using HTML and JavaScript.
function print_r_tree ( $data )
<
// capture the output of print_r
$out = print_r ( $data , true );

// replace something like ‘[element] => (‘ with .

// replace ‘)’ on its own on a new line (surrounded by whitespace is ok) with ‘

// print the javascript function toggleDisplay() and then the transformed output
echo » . «\n $out » ;
>
?>
Pass it a multidimensional array or object and each sub-array/object will be hidden and replaced by a html link that will toggle its display on and off.
Its quick and dirty, but great for debugging the contents of large arrays and objects.
Note: You’ll want to surround the output with

I have written a nice debugging function.
This function handles arrays beautifully.
//Debug variables, $i and $k are for recursive use
function DebugDisplayVar ( $input , $name = «Debug» , $i = «0» , $k = array( «Error» )) <
if( is_array ( $input ))
< foreach ( $input as $i =>$value ) <
$temp = $k ;
$temp [] = $i ;
DebugDisplayVar ( $value , $name , $i , $temp );>
>else < //if not array
echo «$» . $name ; //[$k]
foreach ( $k as $i => $value ) <
if( $value !== «Error» )
>
echo » = $input
» ;
> >

//outputs
Debug [ 0 ] = value
Debug [ 1 ] = another value
ect .

A simple function to send the output of print_r to firebug.
The script creates a dummy console object with a log method for when firebug is disabled/not available.

This is an alternative for printing arrays. It bolds array values.

if ( is_array ( $v )) <
print_array ( $v );
>
else <
echo » $a [ $k ] » ;
>
>
echo ‘) ‘ ;
>
$a1 = array ( «apples» , «oranges» , «pears» );
$a2 = array ( «potatos» , «green beans» , «squash» );
$a3 = array ( «euros» , «dollars» , «pesos» , «dinars» );
$test = range ( 1 , 9 );
array_push ( $test , array ( «fruit» => $a1 , «vegies» => $a2 , «money» => $a3 ));
print_array ( $test , «test» );
?>

I was having problems using print_r because I didn’t like the fact that if tags where included in the array it would still be parsed by the browsers.

Heres a simple fix for anyone who is having the same problem as I did. This will output your text properly for viewing through the browser instead of the browser’s «view source» or CLI.

A slight modification to the previous post to allow for arrays containing mutli line strings. haven’t fully tested it with everything, but seems to work great for the stuff i’ve done so far.

function print_r_reverse (& $output )
<
$expecting = 0 ; // 0=nothing in particular, 1=array open paren ‘(‘, 2=array element or close paren ‘)’
$lines = explode ( «\n» , $output );
$result = null ;
$topArray = null ;
$arrayStack = array();
$matches = null ;
while (!empty( $lines ) && $result === null )
<
$line = array_shift ( $lines );
$trim = trim ( $line );
if ( $trim == ‘Array’ )
<
if ( $expecting == 0 )
<
$topArray = array();
$expecting = 1 ;
>
else
<
trigger_error ( «Unknown array.» );
>
>
else if ( $expecting == 1 && $trim == ‘(‘ )
<
$expecting = 2 ;
>
else if ( $expecting == 2 && preg_match ( ‘/^\[(.+?)\] \=\> (.+)$/’ , $trim , $matches )) // array element
<
list ( $fullMatch , $key , $element ) = $matches ;
if ( trim ( $element ) == ‘Array’ )
<
$topArray [ $key ] = array();
$newTopArray =& $topArray [ $key ];
$arrayStack [] =& $topArray ;
$topArray =& $newTopArray ;
$expecting = 1 ;
>
else
<
$topArray [ $key ] = $element ;
>
>
else if ( $expecting == 2 && $trim == ‘)’ ) // end current array
<
if (empty( $arrayStack ))
<
$result = $topArray ;
>
else // pop into parent array
<
// safe array pop
$keys = array_keys ( $arrayStack );
$lastKey = array_pop ( $keys );
$temp =& $arrayStack [ $lastKey ];
unset( $arrayStack [ $lastKey ]);
$topArray =& $temp ;
>
>
// Added this to allow for multi line strings.
else if (!empty( $trim ) && $expecting == 2 )
<
// Expecting close parent or element, but got just a string
$topArray [ $key ] .= «\n» . $line ;
>
else if (!empty( $trim ))
<
$result = $line ;
>
>

$output = implode ( n , $lines );
return $result ;
>

/**
* @param string $output : The output of a multiple print_r calls, separated by newlines
* @return mixed[] : parseable elements of $output
*/
function print_r_reverse_multiple ( $output )
<
$result = array();
while (( $reverse = print_r_reverse ( $output )) !== NULL )
<
$result [] = $reverse ;
>
return $result ;
>

$output = ‘
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
[3] => Array
(
[nest] => yes
[nest2] => Array
(
[nest] => some more
asffjaskkd
)
[nest3] => o rly?
)
)
)

some extra stuff
‘ ;
var_dump ( print_r_reverse ( $output ), $output );

?>

This should output

print_r(), just like var_dump() does NOT cast an object, not even if it has a __toString() method — which is normal.

class A <
public function __toString () <
return ‘In class A’ ;
>
>
$a = new A ;
echo $a ; // In class A
print_r ( $a ); // A Object()
// you can simulate the echo by casting it manually
print_r ((string) $a ); // In class A

print_r is used for debug purposes. Yet I had some classes where I just wanted the values coming out of the database, not all the other crap. thus i wrote the following function. If your class has an toArray function, that one will be called otherwise it will return the object as is. print_neat_classes_r is the function that should be called!

( $array , $return = false ) <
return print_r ( self :: neat_class_print_r ( $array ), $return );
>

function do_print_r ( $array , $return = false ) <
if( is_object ( $array ) && method_exists ( $array , ‘toArray’ )) <
return $array -> toArray ();
>else if( is_array ( $array )) <
foreach( $array as $key => $obj ) <
$array [ $key ] = self :: do_print_r ( $obj , $return );
>
return $array ;
>else <
return $array ;
>
>
?>

Here is a print_r() clone but support max level limit.

When we want to print a big object, this will help us get a clean dumping data.

/**
* Recrusive print variables and limit by level.
*
* @param mixed $data The variable you want to dump.
* @param int $level The level number to limit recrusive loop.
*
* @return string Dumped data.
*
* @author Simon Asika (asika32764[at]gmail com)
* @date 2013-11-06
*/
function print_r_level ( $data , $level = 5 )
<
static $innerLevel = 1 ;

static $tabLevel = 1 ;

static $cache = array();

$type = gettype ( $data );
$tabs = str_repeat ( ‘ ‘ , $tabLevel );
$quoteTabes = str_repeat ( ‘ ‘ , $tabLevel — 1 );

$recrusiveType = array( ‘object’ , ‘array’ );

// Recrusive
if ( in_array ( $type , $recrusiveType ))
<
// If type is object, try to get properties by Reflection.
if ( $type == ‘object’ )
<
if ( in_array ( $data , $cache ))
<
return «\n < $quoteTabes >*RECURSION*\n» ;
>

// Cache the data
$cache [] = $data ;

$output = get_class ( $data ) . ‘ ‘ . ucfirst ( $type );
$ref = new \ ReflectionObject ( $data );
$properties = $ref -> getProperties ();

foreach ( $properties as $property )
<
$property -> setAccessible ( true );

$pType = $property -> getName ();

if ( $property -> isProtected ())
<
$pType .= «:protected» ;
>
elseif ( $property -> isPrivate ())
<
$pType .= «:» . $property -> class . «:private» ;
>

if ( $property -> isStatic ())
<
$pType .= «:static» ;
>

$elements [ $pType ] = $property -> getValue ( $data );
>
>
// If type is array, just retun it’s value.
elseif ( $type == ‘array’ )
<
$output = ucfirst ( $type );
$elements = $data ;
>

// Start dumping datas
if ( $level == 0 || $innerLevel $level )
<
// Start recrusive print
$output .= «\n < $quoteTabes >(» ;

foreach ( $elements as $key => $element )
<
$output .= «\n < $tabs >[ < $key >] => » ;

// Increment level
$tabLevel = $tabLevel + 2 ;
$innerLevel ++;

$output .= in_array ( gettype ( $element ), $recrusiveType ) ? $self ( $element , $level ) : $element ;

// Decrement level
$tabLevel = $tabLevel — 2 ;
$innerLevel —;
>

// Clean cache
if( $innerLevel == 1 )
<
$cache = array();
>

return $output ;
> // End function

class testClass
<
protected $a = ‘aaa’ ;

public $c = array( 1 , 2 , [ ‘a’ , ‘b’ , ‘c’ ], 4 );

static public $d = ‘ddd’ ;

static protected $e = ‘eee’ ;
>

$test = new testClass ;

$test -> testClass = $test ;

testClass Object
(
[a:protected] => aaa
[b:testClass:private] => bbb
[c] => Array
(
[0] => 1
[1] => 2
[2] => Array
*MAX LEVEL*

[d:static] => ddd
[e:protected:static] => eee
[testClass] =>
*RECURSION*

You cannot use print_r(), var_dump() nor var_export() to get static member variables of a class. However, in PHP5 you can use Reflection classes for this:

= new ReflectionClass ( ‘Static’ );
print_r ( $reflection -> getStaticProperties ());

I use this all the time when debugging objects, but when you have a very large object with big arrays of sub-objects, it’s easy to get overwhelmed with the large amount of output. sometimes you don’t want to see absolutely every sub-object.

I made this function to debug objects while «hiding» sub-objects of certain types. This also color codes the output for a more readable printout.

function wtf ( $var , $arrayOfObjectsToHide = null , $fontSize = 11 )
<
$text = print_r ( $var , true );

if ( is_array ( $arrayOfObjectsToHide )) <

foreach ( $arrayOfObjectsToHide as $objectName ) <

$searchPattern = ‘#(‘ . $objectName . ‘ Object\n(\s+)\().*?\n\2\)\n#s’ ;
$replace = «$1 —> HIDDEN — courtesy of wtf() )» ;
$text = preg_replace ( $searchPattern , $replace , $text );
>
>

// color code objects
$text = preg_replace ( ‘#(\w+)(\s+Object\s+\()#s’ , ‘ $1 $2’ , $text );
// color code object properties
$text = preg_replace ( ‘#\[(\w+)\:(public|private|protected)\]#’ , ‘[ $1 : $2 ]’ , $text );

// example usage:
wtf ( $myBigObject , array( ‘NameOfObjectToHide_1’ , ‘NameOfObjectToHide_2’ ));

If you have to catch the output without showing it at all at first (for example, if you want to append the print_r output to a file), you can do this:

();
print_r ( $some_array );
$output = ob_get_clean ();

// if you want to append the print_r output of $some_array to, let’s say, log.txt:

file_put_contents ( ‘log.txt’ , file_get_contents ( ‘log.txt’ ) . $output )

Another slight modification to the previous post to allow for empty array elements

my take on the highlighted markupped debug function:

/**
* print_array()
* Does a var_export of the array and returns it between » );
>
?>

For those of you needing to print an array within a buffer callback function, I’ve created this quick function. It simply returns the array as a readable string rather than printing it. You can even choose whether to return it in normal text-mode or HTML. It’s recursive, so multi-dimensial arrays are supported. I hope someone finds this useful!

function return_array ( $array , $html = false , $level = 0 ) <
$space = $html ? » » : » » ;
$newline = $html ? «
» : «\n» ;
for ( $i = 1 ; $i 6 ; $i ++) <
$spaces .= $space ;
>
$tabs = $spaces ;
for ( $i = 1 ; $i $level ; $i ++) <
$tabs .= $spaces ;
>
$output = «Array» . $newline . $newline ;
foreach( $array as $key => $value ) <
if ( is_array ( $value )) <
$level ++;
$value = return_array ( $value , $html , $level );
$level —;
>
$output .= $tabs . «[» . $key . «] => » . $value . $newline ;
>
return $output ;
>

Here’s a PHP version of print_r which can be tailored to your needs. Shows protected and private properties of objects and detects recursion (for objects only!). Usage:

void u_print_r ( mixed $expression [, array $ignore] )

Use the $ignore parameter to provide an array of property names that shouldn’t be followed recursively.

function u_print_r ( $subject , $ignore = array(), $depth = 1 , $refChain = array())
<
if ( $depth > 20 ) return;
if ( is_object ( $subject )) <
foreach ( $refChain as $refVal )
if ( $refVal === $subject ) <
echo «*RECURSION*\n» ;
return;
>
array_push ( $refChain , $subject );
echo get_class ( $subject ) . » Object ( \n» ;
$subject = (array) $subject ;
foreach ( $subject as $key => $val )
if ( is_array ( $ignore ) && ! in_array ( $key , $ignore , 1 )) <
echo str_repeat ( » » , $depth * 4 ) . ‘[‘ ;
if ( $key < 0 >== «\0» ) <
$keyParts = explode ( «\0» , $key );
echo $keyParts [ 2 ] . (( $keyParts [ 1 ] == ‘*’ ) ? ‘:protected’ : ‘:private’ );
> else
echo $key ;
echo ‘] => ‘ ;
u_print_r ( $val , $ignore , $depth + 1 , $refChain );
>
echo str_repeat ( » » , ( $depth — 1 ) * 4 ) . «)\n» ;
array_pop ( $refChain );
> elseif ( is_array ( $subject )) <
echo «Array ( \n» ;
foreach ( $subject as $key => $val )
if ( is_array ( $ignore ) && ! in_array ( $key , $ignore , 1 )) <
echo str_repeat ( » » , $depth * 4 ) . ‘[‘ . $key . ‘] => ‘ ;
u_print_r ( $val , $ignore , $depth + 1 , $refChain );
>
echo str_repeat ( » » , ( $depth — 1 ) * 4 ) . «)\n» ;
> else
echo $subject . «\n» ;
>

public $var1 = ‘a’ ;
protected $var2 = ‘b’ ;
private $var3 = ‘c’ ;
protected $array = array( ‘x’ , ‘y’ , ‘z’ );

$test = new test ();
$test -> recursiveRef = $test ;
$test -> anotherRecursiveRef -> recursiveRef = $test ;
$test -> dont -> follow = ‘me’ ;

u_print_r ( $test , array( ‘dont’ ));

test Object (
[var1] => a
[var2:protected] => b
[var3:private] => c
[array:protected] => Array (
[0] => x
[1] => y
[2] => z
)
[recursiveRef] => *RECURSION*
[anotherRecursiveRef] => stdClass Object (
[recursiveRef] => *RECURSION*
)
)

Another attempt that tries to overcome the memory blowout when the passed in data has mutual recursion.

function safe_print_r ( $data , $nesting = 5 , $indent = » ) <
if (! is_object ( $data ) && ! is_array ( $data )) <
var_dump ( $data );
> elseif ( $nesting 0 ) <
echo «** MORE **\n» ;
> else <
echo ucfirst ( gettype ( $data )) . » (\n» ;
foreach ((array) $data as $k => $v ) <
echo $indent . «\t[ $k ] => » ;
safe_print_r ( $v , $nesting — 1 , » $indent \t» );
>
echo » $indent )\n» ;
>
>
?>

A slight amendment to Matt’s awesome print_r_reverse function (Thank You, a life-saver — data recovery 🙂 . If the output is copied from a Windows system, the end of lines may include the return character «\r» and so the scalar (string) elements will include a trailing «\r» character that isn’t suppose to be there. To resolve, replace the first line in the function with.

= preg_split ( ‘#\r?\n#’ , trim ( $in )); ?>

This will work for both cases (Linux and Windows).

I include the entire function below for completeness, but all credit to Matt, the original author, Thank You.

//Author: Matt (http://us3.php.net/print_r)
function print_r_reverse ( $in ) <
$lines = preg_split ( ‘#\r?\n#’ , trim ( $in ));
if ( trim ( $lines [ 0 ]) != ‘Array’ ) <
// bottomed out to something that isn’t an array
return $in ;
> else <
// this is an array, lets parse it
if ( preg_match ( «/(\s<5,>)\(/» , $lines [ 1 ], $match )) <
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match [ 1 ];
$spaces_length = strlen ( $spaces );
$lines_total = count ( $lines );
for ( $i = 0 ; $i $lines_total ; $i ++) <
if ( substr ( $lines [ $i ], 0 , $spaces_length ) == $spaces ) <
$lines [ $i ] = substr ( $lines [ $i ], $spaces_length );
>
>
>
array_shift ( $lines ); // Array
array_shift ( $lines ); // (
array_pop ( $lines ); // )
$in = implode ( «\n» , $lines );
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all ( «/^\s<4>\[(.+?)\] \=\> /m» , $in , $matches , PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
$pos = array();
$previous_key = » ;
$in_length = strlen ( $in );
// store the following in $pos:
// array with key = key of the parsed array’s item
// value = array(start position in $in, $end position in $in)
foreach ( $matches as $match ) <
$key = $match [ 1 ][ 0 ];
$start = $match [ 0 ][ 1 ] + strlen ( $match [ 0 ][ 0 ]);
$pos [ $key ] = array( $start , $in_length );
if ( $previous_key != » ) $pos [ $previous_key ][ 1 ] = $match [ 0 ][ 1 ] — 1 ;
$previous_key = $key ;
>
$ret = array();
foreach ( $pos as $key => $where ) <
// recursively see if the parsed out value is an array too
$ret [ $key ] = print_r_reverse ( substr ( $in , $where [ 0 ], $where [ 1 ] — $where [ 0 ]));
>
return $ret ;
>
>
?>

We had an interesting problem dumping an object that
contained embedded HTML. The application makes use
of buffer manipulation functions, so print_r’s 2nd argument
wasn’t helpful. Here is how we solved the problem:

$object = new ObjectContainingHTML();
$savedbuffercontents = ob_get_clean();
print_r($object);
$print_r_output = ob_get_clean();
ob_start();
echo $savedbuffercontents;
echo htmlentities($print_r_output);

Источник

Читайте также:  Чем отмыть переводные татуировки с кожи ребенку
Оцените статью