PrivateUser
PrivateUser

Reputation: 4524

Remove white spaces in php output

I have some php code. But it outputs some empty spaces in the beginning when I view the source code.

Can someone help me to remove it?

Here is the screenshot

enter image description here

Here is my full code

<?php
include_once dirname(dirname(__FILE__)) . '/wp-load.php';
function dt_query() {
$args = array(
    'post_type' => 'order_guide',
);
$the_query = new WP_Query( $args ); ?>
<?php $dt_array = array(); ?>
<?php if ( $the_query->have_posts() ) : ?>
  <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <?php 
     $dt_array[] = array(
     'glazier' => get_field('glazier'),
     'brand'   => get_field('brand'),
     'pack'   => get_field('pack'),
     'size'   => get_field('size'),
     'description'   => get_field('description'),
     'code'   => '<a href="'.get_field('code').'">Download</a>',
     'cs_price'   => get_field('cs_price'),
     'split'   => get_field('split'),
     );
     ?>
  <?php endwhile; ?>
<?php endif;
echo maybe_serialize($dt_array); ?>
<?php }
dt_query();

Upvotes: 0

Views: 3196

Answers (4)

Geek
Geek

Reputation: 413

The spaces come from the whitespaces between the previous closing ?> tag and the next <?php tag.
Try removing all <?php and ?> tags, but keep the <?php tag on the first line.

Upvotes: 1

binfalse
binfalse

Reputation: 518

Everything between <?php and ?> will be parsed by the PHP interpreter. Everything else is dumped to your output. And that is your problem. You often close ?> followed by a new line and open <?php. Thus, the newline is written to your output and you'll end up with a lot of empty lines. So, why do you close and reopen your PHP workspace that often? Just include all PHP commands in a single PHP environment:

<?php
YOUR COMMANDS
MORE COMMANDS
EVEN MORE COMMANDS
[...]
?>

and the empty lines will vanish :)

Upvotes: 2

Vikash Pathak
Vikash Pathak

Reputation: 3562

you can use $string

// one replcement
$string = str_replace(' ', '', $string);


// for all replacement.
$string = preg_replace('/\s+/', '', $string);

Upvotes: 0

vaibhavmande
vaibhavmande

Reputation: 1111

trim the string before the echo

Upvotes: 1

Related Questions