Home > database >  How to remove Leading white space inside XML file in PHP
How to remove Leading white space inside XML file in PHP

Time:09-26

I have this XML file content:

<?xml version="1.0" encoding="utf-8"?>
<products>
  <item>
    <ItemID>01</ItemID>
    <ItemName>Book</ItemName>
  </item>
  <Product>
    <ProductID>01</ProductID>
    <ProductName>Paper</ProductName>
  </Product>

and want the output like this format to remove the leading white spaces from the beginning of <product> to be like this:

<?xml version="1.0" encoding="utf-8"?>
<products>
  <item>
    <ItemID>01</ItemID>
    <ItemName>Book</ItemName>
  </item><Product>
    <ProductID>01</ProductID>
    <ProductName>Paper</ProductName>
  </Product>

Can I do it in PHP?

Thanks in advance.

CodePudding user response:

This can be optimized in case it's a large file, but it will get you the idea:

<?php
$str = 'your xml content';
  
$lines = explode("\n", $str);
 
echo implode("\n", array_map(function ($line) {
    $trimmedLine = trim($line);
    
    if ($trimmedLine == "<Product>") {
        return $trimmedLine;
    }
    
    return $line;
}, $lines));

https://3v4l.org/2ab10

Edit:

for your updated version, you can do something like this:

$lines = explode("\n", $str);

$output = "";

$arrayLength = count($lines);

for ($i = 0; $i < $arrayLength; $i  ) {
    $trimmedNextLine = isset($lines[$i   1]) ? trim($lines[$i   1]) : null;
    $line = $lines[$i];
    
    if ($trimmedNextLine == "<Product>") {
        $output .= $line . $trimmedNextLine;
        $i  ;
    } else {
        $output .= $line;
    }
    
    if ($i < $arrayLength) {
        $output .= "\n";
    }
}

echo $output;

https://3v4l.org/pQSED

  • Related