简体   繁体   中英

How to get the NodeValue from <td> type input

I am using this HTML and I am trying to parse it to get the nodeValue of all the elements in the table columns.

<table id="custinfo">
    <tr>
        <td><label>First Name</label></td> 
        <td><input type="text" name="firstname" ></td>    
    </tr> 
    <tr>
        <td><label>Last Name</label></td>
        <td><input type="text" name="lastname" ></td>   
    </tr>
    <tr>
        <td><label>Phone Number</label></td> 
        <td><input type="text" name="email" ></td>
    </tr>   
</table>

Here is the PHP It's only working for the labels but not for the input types.

$Dom= new DOMDocument();   
libxml_use_internal_errors(true);
$Dom->loadHTMLFile('Pre_order.html'); 
$info=$Dom->getElementById('custinfo');
$inforows=$info->getElementsByTagName("tr");
$input_tags = $Dom->getElementsByTagName('input'); 
$fnamecol=$inforows->item(0)->getElementsByTagName("td");
$fname=$fnamecol->item(1)->nodeValue; //this is returning null Instead of returning the input text value.

Use simple_dom_parser.php library instead (Download library: https://sourceforge.net/projects/simplehtmldom/files/ & docs: http://simplehtmldom.sourceforge.net/ )

require_once('simple_dom_parser.php');

// Create DOM from file
$html = file_get_html('Pre_order.html');


// Find all labels
foreach($html->find('label') as $label)
       echo $label->plaintext . '<br>';


// Find all inputs
foreach($html->find('input') as $input)
       echo $input->name . '<br>'; 

After actually adding values to the input elements, try the following

$input_tags->item(1)->getAttribute('value')

(Btw, check the case of $Dom and $dom in your examples.)

Here's some sample code that works when executed at http://sandbox.onlinephpfunctions.com/ :

<?php

$htmlString = <<<HTML
<table id="custinfo">
    <tr>
        <td><label>First Name</label></td> 
        <td><input type="text" name="firstname" value="Jane"></td>    
    </tr> 
    <tr>
        <td><label>Last Name</label></td>
        <td><input type="text" name="lastname" value="Doe"></td>   
    </tr>
    <tr>
        <td><label>Phone Number</label></td> 
        <td><input type="text" name="email" value="212-555-1212"></td>
    </tr>   
</table>
HTML;

$dom= new DOMDocument();
$dom->loadHTML($htmlString); 
$input_tags = $dom->getElementsByTagName('input'); 

echo $input_tags->item(1)->getAttribute('value'); // "Doe"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM