How do I read an XML with HTML markup

1

I have an XML where inside it has a complete table. How do I read this XML and already print this Table structure in html?

I'm working on PHP

XML

<document page-count="1">
    <page number="1">
        <table data-filename="p01.pdf" data-page="1" data-table="1">
            <tr>
                <td></td>
                <td colspan="6">FULANO DE TAL</td>
            </tr>
        </table>
    </page>
</document>
    
asked by anonymous 05.10.2018 / 05:49

2 answers

-1

Are you already using any PHP library? If not, try using SimpleXML .

<?php
    $xml = simplexml_load_file('arq.xml');

    foreach ($xml->children() as $page){

        foreach($page->children() as $table){
            echo "<table";

            foreach($table->attributes() as $att => $valor){
                echo " $att='$valor'";
            }

            echo " style='border: 1px solid black'>";

            foreach($table->children() as $tr){

                echo "<tr>";

                foreach($tr->children() as $td){
                    echo "<td>";
                    echo $td;
                    echo "</td>";
                }

                echo "</tr>";
            }

            echo "</table>";
        }

        echo "<br>Página ". $page["number"];
        echo "<br>";
    }
?>

Will print:

<table data-filename='p01.pdf' data-page='1' data-table='1' style='border: 1px solid black'>
  <tr>
    <td></td>
    <td>FULANO DE TAL</td>
  </tr>
</table>
<br>
Página 1
<br>
    
05.10.2018 / 16:37
4

Using a series of foreach for something like this is to take an immense turn into something that can be solved simply, using DOMDocument::saveHTML combined with DOMDocument::getElementsByTagName

More efficient example without loops:

$dom = new DOMDocument();
$dom->load('arq.xml');

$tables = $dom->getElementsByTagName('table');

if ($tables->length) {
    $table = $tables->item(0);//Pega a primeira tabela
    echo $dom->saveHTML($table); //Exibe o conteudo da tabela
} else {
    echo 'Tabela não encontrada';
}

Sample test online: link

Documentation for useful functions for manipulating DOM with PHP:

  • upload an XML file or stream: link
  • Load a string in XML format: link
  • Load a string in HTML format : link
  • Load a string in HTML format : link
  • element by the ID: link
  • Get one or more elements ( DOMNodeList ) for tag name: link
  • Get one or more elements ( DOMNodeList ) for the name of the tag that uses the document's namespace: link
  • Returns the DOM content as a string in XML format: link
  • Returns the DOM content as a string in HTML format: link
05.10.2018 / 17:05