php print r в файл
Функция print_r()
Функция print_r – выводит удобочитаемую информацию о переменной, используется при отладке программ.
Давайте рассмотрим пример, как работает эта функция:
В этом простом примере функция print_r просто вернула значение переменной. Пользы от функции print_r в данном случае мало, но её используют обычно для просмотра массивов.
В следующем примере мы используем функцию print_r для просмотра массива:
В данном случа мы передали в функцию массив, в который вложили другой массив. Полученный результат читать не очень удобно, так как браузер не показывает переносы строк. Чтобы увидеть обещенный удобочитаемый результат, нужно просмотреть html-код страницы, или добавить тег pre перед функцией.
В следующем примере мы только добавим тег pre к предыдущему, чтобы увидеть отличия:
Теперь результат действительно удобочитаемый.
Перехват вывода print_r
Давайте рассмотрим пример перехвата вывода функции print_r() :
Результат работы этого кода полностью аналогичен предыдущему примеру.
Функции print_r и var_dump
Функция print_r() выводит удобочитаемую, но не полную информацию о переменной. Например попробуем вывести несуществующую переменную:
Функция print_r() тут ничего не вывела.
При отладке программ, а функции print_r() и var_dump() используются при отладке, иногда важно знать типы переменных, а иногда хочется увидеть красиво представленный массив без лишней информации. В зависимости от этого и пользуются той или иной функцией.
Php print r в файл
Бывалый
Профиль
Группа: Участник
Сообщений: 246
Регистрация: 24.10.2006
Где: Санкт-Петербург
Репутация: нет
Всего: 1
Здравствуйте.
Можно ли сделать так, чтобы в файл записывался массив в том виде в котором он выводится функцией print_r(), т.е. в виде:
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
M Mal Hack | Название темы должно отражать ее суть |
Опытный
Профиль
Группа: Участник
Сообщений: 473
Регистрация: 30.12.2006
Репутация: 7
Всего: 18
Эксперт
Профиль
Группа: Участник Клуба
Сообщений: 1046
Регистрация: 10.1.2007
Где: Санкт-Петербург
Репутация: 19
Всего: 54
Опытный
Профиль
Группа: Участник
Сообщений: 723
Регистрация: 4.1.2005
Репутация: 6
Всего: 18
Бывалый
Профиль
Группа: Участник
Сообщений: 246
Регистрация: 24.10.2006
Где: Санкт-Петербург
Репутация: нет
Всего: 1
Код |
‘apple’, ‘b’ => ‘banana’, ‘c’ => array (‘x’, ‘y’, ‘z’)); ob_start(); print_r($a); file_put_contents(‘test.txt’, ob_end_contents()); ob_end_clean(); ?> |
Эксперт
Профиль
Группа: Участник Клуба
Сообщений: 1046
Регистрация: 10.1.2007
Где: Санкт-Петербург
Репутация: 19
Всего: 54
Если у тебя PHP5, то
Бывалый
Профиль
Группа: Участник
Сообщений: 246
Регистрация: 24.10.2006
Где: Санкт-Петербург
Репутация: нет
Всего: 1
Мудрый.
Профиль
Группа: Участник Клуба
Сообщений: 9926
Регистрация: 15.2.2004
Репутация: 122
Всего: 261
Эксперт
Профиль
Группа: Участник Клуба
Сообщений: 1046
Регистрация: 10.1.2007
Где: Санкт-Петербург
Репутация: 19
Всего: 54
Цитата(Mal Hack @ 18.1.2007, 15:58 |
Мне вот интересно, а как это будет работать, если print_r возвращает bool значение, а не то, что вывел? |
Это работает и очень даже корректно.
Цитата(PHP.NET) |
If you would like to capture the output of print_r(), use the return parameter. If this parameter is set to TRUE, print_r() will return its output, instead of printing it (which it does by default). |
Замечание: This function internally uses the output buffering with this parameter so it can not be used inside ob_start() callback function.
Пример 1. return parameter example
‘monkey’, ‘foo’ => ‘bar’, ‘x’ => array (‘x’, ‘y’, ‘z’));
$results = print_r($b, true); //$results now contains output from print_r
?>
Замечание: If you need to capture the output of print_r() with a version of PHP prior to 4.3.0, use the output-control functions.
[ Время генерации скрипта: 0.1222 ] [ Использовано запросов: 21 ] [ GZIP включён ] Php print r в файлВ этом разделе помещены уроки по PHP скриптам, которые Вы сможете использовать на своих ресурсах. Фильтрация данных с помощью zend-filterКогда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных. Контекстное экранирование с помощью zend-escaperОбеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода. Подключение Zend модулей к ExpressiveExpressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей. Совет: отправка информации в Google Analytics через APIПредположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке. Подборка PHP песочницПодборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт. Совет: активация отображения всех ошибок в PHPПри поднятии PHP проекта на новом рабочем окружении могут возникнуть ошибки отображение которых изначально скрыто базовыми настройками. Это можно исправить, прописав несколько команд. АгентPHP парсер юзер агента с поддержкой Laravel, работающий на базе библиотеки Mobile Detect. Print array to a fileI would like to print an array to a file. I would like the file to look exactly similar like how a code like this looks. Is there any one lines solution for this rather than regular for each look. 13 Answers 13Either var_export or set print_r to return the output instead of printing it. Just use print_r ; ) Read the documentation: So this is one possibility: file_put_contents($file, print_r($array, true), FILE_APPEND) Quick and simple do this: I just wrote this function to output an array as text: Should output nicely formatted array. Beware of user input. This script was created for internal use. If you intend to use this for public use you will need to add some additional data validation to prevent script injection. This is not fool proof and should be used with trusted data only. The following function will output something like: here is the function (note: function is currently formatted for oop implementation.) Alternately you can use this script I also wrote a while ago: This one is nice to copy and paste parts of an array. ( Would be near impossible to do that with serialized output ) Not the cleanest function but it gets the job done. This one will output as follows: Also take care for user input. Here is the code. However op needs to write array as it is on file I have landed this page to find out a solution where I can write a array to file and than can easily read later using php again. I have found solution my self by using json_encode so anyone else is looking for the same here is the code: Here is what I learned in last 17 hours which solved my problem while searching for a similar solution. resources: Second Resource is the code in one of the answers above: This is the second thing I didn’t knew, FILE_APPEND. What I was trying to achieve is get contents from a file, edit desired data and update the file with new data but after deleting old data. Now I only need to know how to delete data from file before adding updated data. About other solutions: Just so that it may be helpful to other people; when I tried var_export or Print_r or Serialize or Json.Encode, I either got special characters like => or ; or ‘ or [] in the file or some kind of error. Tried too many things to remember all errors. So if someone may want to try them again (may have different scenario than mine), they may expect errors. About reading file, editing and updating: I used fgets() function to load file array into a variable ($array) and then use unset($array[x]) (where x stands for desired array number, 1,2,3 etc) to remove particular array. Then use array_values() to re-index and load the array into another variable and then use a while loop and above solutions to dump the array (without any special characters) into target file. print_r(PHP 4, PHP 5, PHP 7, PHP 8) print_r — Выводит удобочитаемую информацию о переменной Описаниеprint_r() выводит информацию о переменной в удобочитаемом виде. Список параметровВыражение для вывода на экран. Возвращаемые значенияПримерыПример #1 Пример использования print_r() Результат выполнения данного примера: Пример #2 Пример использования параметра return ПримечанияСмотрите такжеUser Contributed Notes 36 notesI 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. 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. I always use this function in my code, because most of my functions return an Array or Boolean : ?> ( 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. ): The following will output an array in a PHP parsable format: Here is a print_r that produces xml: // replace ‘)’ on its own on a new line (surrounded by whitespace is ok) with ‘ A simple function to send the output of print_r to firebug. This is an alternative for printing arrays. It bolds array values. 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. $output = ‘ ?> This should output 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! 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. $test = new testClass ; testClass Object [d:static] => ddd 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: 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. 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: Another slight modification to the previous post to allow for empty array elements my take on the highlighted markupped debug function: /** 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! 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: test Object ( Another attempt that tries to overcome the memory blowout when the passed in data has mutual recursion. I include the entire function below for completeness, but all credit to Matt, the original author, Thank You. We had an interesting problem dumping an object that
|