Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading whitespace from xml using php

Tags:

php

xml

I need to remove leading white space in below xml,

1
2 <?xml version="1.0" encoding="UTF-8"?>
3 <VAST version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vast.xsd">
4 </VAST>

I get above xml in variable like $html and using trim() function to remove leading white space in xml ex : echo trim($html),but it does not remove space. Anyhelp appreciated

like image 552
Thiyagu Avatar asked Feb 16 '26 01:02

Thiyagu


1 Answers

trim only removes specific whitespace characters from a string. However if your string contains other non-rendered characters it will not work.

A candidate for this is the BOM (Byte Order Mark). It is interpreted but not rendered by the browser. So it will not be visible. The bytes itself are not part of the characters that trim() or ltrim() would remove.

Here is an example:

$string = "\xEF\xBB\xBF\r\n<foo/>";
var_dump(trim($string));

Output:

string(11) "
<foo/>"

If you know that the string is XML you can use string function to remove anything before the first <.

$string = substr($string, strpos($string, '<'));
var_dump($string);

Output:

string(6) "<foo/>"
like image 68
ThW Avatar answered Feb 18 '26 14:02

ThW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!