Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making print_r use PHP_EOL

Tags:

php

eol

My PHP_EOL is "\r\n", however, when I do print_r on an array each new line has a "\n" - not a "\r\n" - placed after it.

Any idea if it's possible to change this behavior?

like image 203
neubert Avatar asked Feb 12 '23 13:02

neubert


2 Answers

If you look the source code of print_r you'll find:

PHP_FUNCTION(print_r)
{
    zval *var;
    zend_bool do_return = 0;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &var, &do_return) == FAILURE) {
        RETURN_FALSE;
    }

    if (do_return) {
        php_output_start_default(TSRMLS_C);
    }

    zend_print_zval_r(var, 0 TSRMLS_CC);

    if (do_return) {
        php_output_get_contents(return_value TSRMLS_CC);
        php_output_discard(TSRMLS_C);
    } else {
        RETURN_TRUE;
    }
}

ultimately you can ignore the stuff arround zend_print_zval_r(var, 0 TSRMLS_CC); for your question.

If you follow the stacktrace, you'll find:

ZEND_API void zend_print_zval_r(zval *expr, int indent TSRMLS_DC) /* {{{ */
{
    zend_print_zval_r_ex(zend_write, expr, indent TSRMLS_CC);
}

which leads to

ZEND_API void zend_print_zval_r_ex(zend_write_func_t write_func, zval *expr, int indent TSRMLS_DC) /* {{{ */
{
    switch (Z_TYPE_P(expr)) {
        case IS_ARRAY:
            ZEND_PUTS_EX("Array\n");
            if (++Z_ARRVAL_P(expr)->nApplyCount>1) {
                ZEND_PUTS_EX(" *RECURSION*");
                Z_ARRVAL_P(expr)->nApplyCount--;
                return;
            }
            print_hash(write_func, Z_ARRVAL_P(expr), indent, 0 TSRMLS_CC);
            Z_ARRVAL_P(expr)->nApplyCount--;
            break;

From this point on, you could continue to find the relevant line - but since there is already a hardcoded "Array\n" - i'll assume the rest of the print_r implementation uses the same hardcoded \n linebreak-thing.

So, to answer your question: You cannot change it to use \r\n. Use one of the provided workarounds.

Sidenode: Since print_r is mainly used for debugging, this will do the job as well:

echo "<pre>";
print_r($object);
echo "</pre>";
like image 149
dognose Avatar answered Feb 15 '23 01:02

dognose


Use second param in print_r (set true), read DOC: http://www.php.net/manual/en/function.print-r.php

See: mixed print_r ( mixed $expression [, bool $return = false ] );

Example:

$eol = chr(10); //Break line in like unix
$weol = chr(13) . $eol; //Break line with "carriage return" (required by some text editors)
$data = print_r(array(...), true);
$data = str_replace(eol, weol, $data);
echo $data;
like image 43
Guilherme Nascimento Avatar answered Feb 15 '23 02:02

Guilherme Nascimento