I'm trying to print out form input using getElementById but it doesn't seem to work. Please help.

<?php

$strhtml = 'DomDoc.html';
// create the DOMDocument object, and load HTML from a string
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);

// get the element with id="dv1"
$elm = $dochtml->getElementById('name');

// get the tag name, and content
$cnt = $elm->nodeValue;

echo $cnt;



<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form action="DomDoc.php" method="post">
    <input id="name" type="text" name="">
    <input type="submit" value="Submit">
</form>
</body>
</html>

`

Dani AI

Generated

Short summary and practical fixes for the symptoms in this thread

The reason your <div> prints but the <input> does not is twofold: (1) an element’s visible text is returned via the node/text content, whereas an <input> is an empty (void) element whose typed/default value lives in the value attribute — read that with getAttribute('value'), not nodeValue. (2) PHP’s DOM getElementById() only works when the document declares an ID type (DTD or explicit id registration); otherwise use XPath or attribute checks. (php.net)

Also remember the server-side workflow: loading the HTML file with DOMDocument reads the static file on disk — it will never contain what a user typed into the browser at submit time. The browser only sends controls that have a name (successful controls), so values from inputs without name never arrive in $_POST. If your goal is to insert submitted values into MySQL, read them from $_POST (or php://input for non-form encodings) after ensuring inputs have name attributes. (php.net)

Practical options (pick one)

  • Fast client-side fix (no mass-edit): copy idname on submit with JavaScript so the browser includes values in the POST. Example (attach to the page you serve):

    document.querySelector('form').addEventListener('submit', function () {
      this.querySelectorAll('input,textarea,select').forEach(function(el){
        if (!el.name && el.id && el.type !== 'radio') el.name = el.id;
      });
    });

    Caveat: radios/checkbox groups need coordinated names (copying unique IDs will break grouping).

  • Robust server-side preprocessing: parse each form HTML with DOMDocument/DOMXPath, add name attributes where safe (copy id → name) and save/serve that version. This avoids brittle regex and handles edge cases more cleanly. For runtime reading of default values from an HTML source use DOMXPath::query() or DOMElement::getAttribute('value'). (php.net)

Notes: and were right that loading the file won’t capture submitted data; ’s bulk-edit idea is valid, but prefer DOM or client-side fixes to simple regex for reliability (especially for radio groups and existing names).

Recommended Answers

All 13 Replies

as @diafol said use loadhtmlfile instead

$file = $DOCUMENT_ROOT. "DomDoc.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$elements = $doc->getElementsByTagName('name');
echo $elements->nodeValue;

Thanks. When I call the nodeValue for the div it works but not for the input. I'm trying to send form input by Id to the database.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div id="divID" name="notWorking">This is not working!</div>
<form action="DomDoc.php" method="post">
    <input id="name" type="text" name="">
    <input type="submit" value="Submit">
</form>
</body>
</html>



<?php
$dom = new DOMDocument();
$dom->loadHTMLFile('DomDoc.html');
$div = $dom->getElementById('divID');

echo $div->nodeValue;

?>



<?php
$file = $DOCUMENT_ROOT. "DomDoc.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$elements = $doc->getElementById('name');
echo $elements->nodeValue;
?>

When I call the nodeValue for the div it works but not for the input.

What exactly does not work? The input with ID name does not have a value, is that your issue?

Yes. Even when I put a default value or I input one from the form itself.

What do you mean "input from the form itself"? That can't work as you are loading the HTML from a file.

I have a feeling you want to do something other than we think you want.

I am trying to send data put in the form to mysql database. But Instead of using
$_POST['']
I want to use getElementById('')

Figured as much. The HTML does not get POSTed as a whole to your script, so there is no way to get what you want like that (unless you use Javascript to send the whole DOM, something I don't recommend).

Member Avatar for Member #120589

I am trying to send data put in the form to mysql database. But Instead of using
$_POST['']
I want to use getElementById('')

As prit says. But why are you trying to avoid $_POST ? Makes no sense to me. You've misunderstood the point of DOMDoc in this context. Input data is sent to the server usually by POST or GET methods (form, cURL, url querystring, Ajax etc). This is then picked up in the $_POST or $_GET variables.

If you want to do this for cosmetic reasons, then change $_POST to something else, e.g.

$form = $_POST;

You could even do something like this:

//create faux $_POST data:

$_POST['free'] = 1;
$_POST['me'] = 2;
$_POST['to'] = 3;
$_POST['create'] = 4;
$_POST['an'] = 5;
$_POST['object'] = 6;

$form = (object) $_POST;

echo $form->me;
echo $form->create;

Ok thanks I'm just following orders. The forms I was given don't have name attributes in order for me to use &_POST. This will require me adding a thousand name attributes to each input field everytime the form is changed.

Member Avatar for Member #120589

What flavour of imbecile doesn't put a name att on the fields? I'm assuming there are 'id' atts. If so, with a decent editor, you could do a smart regex replace:

id="..." to id="..." name="..."

I'll have a play and see if I can get one sorted. However - it will NOT work for all inputs - grouped option buttons need the same name, but they can't have the same id (obviously).

In addition, you'll need to check that you're not adding a name that may already exist elsewhere in the form for a different purpose.

Thanks

Member Avatar for Member #120589

OK, here's a rough and ready preg_replace you can use from a php file.

replace.php

function addName($file, $mode='view')
{
    if(!file_exists($file))
    {
        echo "FILE DOES NOT EXIST";
        return false;
    }

    $f = file_get_contents('form.html');
    $pattern = '#((id)(\s*\=\s*)(["|\']\w*["|\']))#';
    $replacement = "$1 name$3$4";
    $n = preg_replace($pattern,$replacement,$f);
    if($mode == 'write') {
        echo (file_put_contents('form.html', $n) !== false) ? '<h3>FILE CHANGED</h3>' : '<h3>FILE WRITE ERROR</h3>';
    }
    echo "<pre>BEFORE:\n" . htmlentities($f) . "\n\n\nAFTER:\n";
    echo htmlentities($n) . '</pre>';
}


addName('form.html'); //2nd param = nothing or 'write' (back to file) or 'view' (same as nothing)

form.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<form>
    <input id = 'blah1' value="10" />
    <input id='blah2' value="20" />
    <input id = "blah3" value="30" />
    <input id="blah4" value="40" />
    <input id= 'blah5' value="50" />
    <input id= "blah6" value="60" />
    <input id ='blah7' value="70" />
    <input id ="blah8" value="80" />
    <input id   = 'blah9' value="90" />

</form>
</body>
</html>

So all you need to do is locate the form files and place the relative reference (relative path) into the function and run it:

addName('../forms/form34.html');

Still not sure I understood this:

This will require me adding a thousand name attributes to each input field everytime the form is changed.

Each input field should only ever have one name attribute. When you say "form is changed", what do you mean?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.