Creating PHP object from HTML

Asked

Viewed 158 times

8

I imagine frameworks usually do the following to create a simple text field:

$campoTexto = new CampoTexto("nomeDoCampo", "valorDoCampo");
$campoTexto->gera();

The result would be:

<input type="text" name="nomeDoCampo" value="valorDoCampo">

My question is the following, is there any class/function that does a reverse engineering of the above code? I imagine something like this:

$tag = new ObjetoMilagroso("<input type=\"text\" name=\"nomeDoCampo\" value=\"valorDoCampo\">");
print $tag->type . " - " . $tag->name . " - " .$tag->value;

The result:

input - fieldName - fieldValue

  • 1

    Very interesting you could create a library with functions of this type to download NET.

  • 3

    This is possible with a parser of HTML (as DOMDocument), but are you sure you need it? There’s no way around it?

  • 3

    From a look at xml processors, after all html is an "xml", with its tags and attributes

  • Is there an objective or is it just curiosity? It is even possible to build a specific domain framework, but it would take a certain amount of work.

1 answer

4

With the suggestion of Fernando I came to the following conclusion:

<?php
    $t = "<input type=\"text\" name=\"nomeDoCampo\" value=\"valorDoCampo\" peterson=\"bonito\" />";
    $html = simplexml_load_string(html_entity_decode($t));
    $arrAtributos = $html[0]->attributes();
    $nome = $html[0]->getName();
    print "Nome da tag: ".$nome."<br />";
    print "Atributos:<br />";
    foreach ($arrAtributos as $key => $value) {
        print $key." => ".$value."<br>";
    }

It’s a simple suggestion yet and needs adjustments, like:

The tag must be closed as in XML (again, Fernando’s suggestion):

<input> =  erro
<input /> = ok
<button></button> = ok

I’m not making mistakes.

But I found it interesting because it ended up being "generic" and solves my problem.

  • 2

    Missing the implementation of the Miracle class :)

  • 1

    kkkk, "again, Fernando’s suggestion," ours seems to be my fault. But I don’t know what you want to use it for, but it’s very interesting, and for further research, (I don’t know it very well) but I believe that html validators use something like that. I don’t know if this is your implementation. But you can search to better understand how your implementation might be.

Browser other questions tagged

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