How do I read an XML with HTML markup

Asked

Viewed 495 times

1

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

I am working in 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>

2 answers

4

Use a series of foreach for something like this is to take an immense turn in something that can be solved in a simple way, if use DOMDocument::saveHTML combined with DOMDocument::getElementsByTagName

More efficient and loopless example:

$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';
}

Online example for testing: https://repl.it/@inphinit/innerhtml-outerhtml-in-php

Documentation for useful functions for handling DOM with PHP:

-1


Are you already using a PHP library? Otherwise, 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>

  • You can change the echo "<table" which starts the HTML element to "<". $table->getName(), for example. So it always accompanies the elements that are in XML

Browser other questions tagged

You are not signed in. Login or sign up in order to post.