2

What im trying to do is load a form and create elements inside it but i end up with something like this:

<form id="form_54" accept-charset="utf-8"></form><input type="text" name="name">

The outpot i'm lookin for is:

<form id="form_54" accept-charset="utf-8"><input type="text" name="name"></form>

this is my function:

public function input($name, $attributes = array(), $type = 'text')
{
    $form = new DOMDocument();
    $form->loadXML($this->doc->saveHTML());

    $input = $form->createElement('input');
    $input->setAttribute('type', $type);
    $input->setAttribute('name', $name);

    if(isset($attributes))
    {
        foreach($attributes as $attr => $val)
        {
            $input->setAttribute($attr, $val);
        }
    }

    $form->appendChild($input);
    $this->doc->loadXML($form->saveHTML());
}

Correct function thanks to Ghost:

public function input($name, $attributes = array(), $type = 'text')
{
    $form = $this->doc->getElementsByTagName('form')->item(0);

    $input = $this->doc->createElement('input');
    $input->setAttribute('type', $type);
    $input->setAttribute('name', $name);

    if(isset($attributes))
    {
        foreach($attributes as $attr => $val)
        {
            $input->setAttribute($attr, $val);
        }
    }

    $form->appendChild($input);
    $this->doc->appendChild($form);
}
2
  • 1
    so whats the problem? Commented Apr 28, 2015 at 12:51
  • Where are you adding form? Is it already in DOM? Commented Apr 28, 2015 at 12:57

1 Answer 1

1

Most likely you're appending on the parent element instead of the form. Try to target the form first, then making the append.

public function input($name, $attributes = array(), $type = 'text')
{
    $dom = new DOMDocument();
    $dom->loadXML($this->doc->saveHTML());
    // target the form
    $form = $dom->getElementsByTagName('form')->item(0);

    $input = $dom->createElement('input');
    $input->setAttribute('type', $type);
    $input->setAttribute('name', $name);

    if(isset($attributes))
    {
        foreach($attributes as $attr => $val)
        {
            $input->setAttribute($attr, $val);
        }
    }

    $form->appendChild($input);
    $this->doc->loadXML($form->saveHTML());
}
Sign up to request clarification or add additional context in comments.

2 Comments

your solution didn't work. however the getElementsByTagName('form')->item(0); that you mentioned was what i needed. so i ended up with the correct function with i added to my question. Thank You!
@jailbird.phoenix oh yeah, i forgot the instance of of your object was inside ->doc, anyway glad this helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.