Jump to content

2 DOMDocument Questions


jay20aiii

Recommended Posts

Hi i'm new to PHP and the forum. I am working on a email script. In it I am using the following to highlight any Input values the user forgot to fill in.

$html = file_get_contents("page.html");
$document = new DOMDocument();
@$document->loadHTML($html);
if (empty($_POST['txtEmail'])) { 
$document->getElementById('email')->setAttribute('style', "color: #ff0000");
} else { 
$document->getElementById('txtEmail')->setAttribute('value', $_POST['txtEmail']);
}
print_r($document->saveHTML());

I have two questions...

 

1). I read print_r should be used primarily for debugging. Should I save the html changes to file and then navigate to that file.. Something like:

$document->saveHTMLFile('somepage.html');
header('Location: http://www.domain.com/somepage.html');

Or is there in fact a better, or more suitable, way using only PHP?

 

2). In my snippet I can update the color of a Label element if a value is missing, or populate the previous Post value if it was present (but a different required value was missing). But how would I go about selecting the option of a Select element? e.g. if my html was:

<label id="title"><span class="fieldname">Title:</span>
<select id="txtTitle" name="txtTitle">
  <option value="">Select</option>
  <option value="DR">Dr </option>
  <option value="MR">Mr</option>
  <option value="MRS">Mrs</option>
  <option value="MS">Ms</option>
  <option value="MISS">Miss</option>
  <option value="OTHER">Other</option>
</select>
</label>

and the post data of txtTitle was "Mr", how would I select Mr in the DomDocument e.g. how would I ammend this line:

<option value="MR">Mr</option>

to this:

<option value="MR" selected="selected">Mr</option>

Hope I was clear.
Thanks
Jay

Link to comment
https://forums.phpfreaks.com/topic/284275-2-domdocument-questions/
Share on other sites

1. print_r() is only for debugging. Not "primarily". Only. It's a string. Just output the string with an echo or print.

2. Find the appropriate

1). Thanks

2). Can you tell me where I am going wrong on this loop:

$element = $document->getElementById('txtTitle');
$options = $element->getElementsByTagName("option");
foreach($options as $option) {
    if ($option->textContent = $_POST['txtTitle']) {        
        $option->setAttribute("selected", "selected");
    }
}

The resulting html has an empty "selected" attribute on every Option tag.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.