2010-09-28 32 views
6

Tôi đang xem qua tệp định nghĩa xml và tôi có DOMNodeList mà tôi đang xem qua. tôi cần phải trích xuất các nội dung của một thẻ con có thể có hoặc không có thể trong thực thể hiệnNhận thẻ con cụ thể từ DOMElement trong PHP

<input id="name"> 
    <label>Full Name:</label> 
    <required /> 
</input> 
<input id="phone"> 
    <required /> 
</input> 
<input id="email" /> 

tôi cần phải thay thế ????????????? với thứ gì đó mang lại cho tôi nội dung của thẻ nhãn nếu nó tồn tại.

Code:

foreach($dom->getElementsByTagName('required') as $required){ 
    $curr = $required->parentNode; 

    $label[$curr->getAttribute('id')] = ????????????? 
} 

Dự kiến ​​kết quả:

Array(
    ['name'] => "Full Name:" 
    ['phone'] => 
) 

Trả lời

8

Lạ một điều là: bạn đã biết câu trả lời vì bạn đã sử dụng nó trong kịch bản của bạn, getElementsByTagName().
Nhưng lần này không phải với DOMDocument như bối cảnh "nút" nhưng với sự input DOMElement:

<?php 
$doc = getDoc(); 
foreach($doc->getElementsByTagName('required') as $e) { 
    $e = $e->parentNode; // this should be the <input> element 
    // all <label> elements that are direct children of this <input> element 
    foreach($e->getElementsByTagName('label') as $l) { 
    echo 'label="', $l->nodeValue, "\"\n"; 
    } 
} 

function getDoc() { 
    $doc = new DOMDocument; 
    $doc->loadxml('<foo> 
    <input id="name"> 
     <label>Full Name:</label> 
     <required /> 
    </input> 
    <input id="phone"> 
     <required /> 
    </input> 
    <input id="email" /> 
    </foo>'); 
    return $doc; 
} 

in label="Full Name:"

+0

Rock, mà sẽ làm điều đó, Cảm ơn bạn! –

Các vấn đề liên quan