Search code examples
phphtmlformattingpre

Format plain text values in columns using \t in php


I have the following code in php, when i execute it:

<pre>
<?php
$input = '<xml>
<user>
    <name>sujit agarwal</name>
    <age>22</age>
    <gender>male</gender>
</user>
<user>
    <name>ajay rana</name>
    <age>25</age>
    <gender>male</gender>
</user>
<user>
    <name>pratap singh</name>
    <age>27</age>
    <gender>male</gender>
</user>
<user>
    <name>asdfasdfasdfasdf</name>
    <age>30</age>
    <gender>male</gender>
</user>
</xml>';
$sx = simplexml_load_string($input);
foreach($sx as $val)
echo $val->name."\t".$val->gender."\t".$val->age."\n";
?>
</pre>

THE OUTPUT IS

sujit agarwal   male    22
ajay rana   male    25
pratap singh    male    27
asdfasdfasdfasdf    male    30

now, my problem is how to align all the gender values and age values in a column even if a name is longer than the rest. Hope i made my problem clear. This is to be done within the PRE tags. because i will later save this to a TXT file

NEEDED FORMATTING

sujit agarwal       male    22
ajay rana           male    25
pratap singh        male    27
asdfasdfasdfasdf    male    30

Solution

  • <?php
    $input = '<xml>
    <user>
        <name>sujit agarwal</name>
        <age>22</age>
        <gender>male</gender>
    </user>
    <user>
        <name>ajay rana</name>
        <age>25</age>
        <gender>male</gender>
    </user>
    <user>
        <name>pratap singh</name>
        <age>27</age>
        <gender>male</gender>
    </user>
    <user>
        <name>asdfasdfasdfasdf</name>
        <age>30</age>
        <gender>male</gender>
    </user>
    </xml>';
    $sx = simplexml_load_string($input);
    
    $output='';
    foreach($sx as $val){
        $values[] = $val->name;
        $values[] = $val->gender;
        $values[] = $val->age;
        $output.=vsprintf("%-30s %s\t %d",$values)."\n";
        $values='';
    }
    
    echo '<pre>';
    echo $output;
    echo '</pre>';
    ?>
    

    outputs:

    sujit agarwal                  male  22
    ajay rana                      male  25
    pratap singh                   male  27
    asdfasdfasdfasdf               male  30