hek2mgl の適切で適切なアドバイスを拡張して、少しだけ問題を解決するのに役立つことを願っています。私はそれが学習などであることを理解していますが、これが正しく行われた場合、ループはまったく必要ありません (もちろん、ログインしようとしている現在の従業員 1 人だけにアクセスする必要があると仮定します)。hek2mgl がリンクしているチュートリアルでは、述語とは何かを示しています。述語を使用して、ユーザーが入力したユーザー名を介して xpath クエリで正しい従業員をすぐに自動選択し、パスワードとパスワードを比較する必要があります。ユーザーによって入力され、それらが一致するかどうかを確認します。この方法では、$result の長さについて何も知る必要はありません (もちろん、有効な長さが 1 であることを除いて)。すべての従業員要素を含むxmlファイルに「従業員」という名前のルートコンテナ要素があると仮定します
<?php
//below is php heredoc string.
//just a simulation of an employees.xml file which
//obviously contains multiple employee elements
//within a root 'employees' element
$xmlStr = <<<XMLBookendMarker
<employees>
<employee ssnum="555662222">
<first_name></first_name>
<last_name></last_name>
<contact_info>
<office_phone></office_phone>
<email></email>
<cell_phone></cell_phone>
</contact_info>
<access_info level="user">
<username>jackass</username>
<password>letmein</password>
</access_info>
<department></department>
<date_started></date_started>
<position></position>
</employee>
<employee ssnum="555991111">
<first_name></first_name>
<last_name></last_name>
<contact_info>
<office_phone></office_phone>
<email></email>
<cell_phone></cell_phone>
</contact_info>
<access_info level="user">
<username>god</username>
<password>qwerty</password>
</access_info>
<department></department>
<date_started></date_started>
<position></position>
</employee>
</employees>
XMLBookendMarker;
//below is the information entered by the user,
//which we will use to find the username in the
//employees.xml and then check if the password matches
$enteredUsername = 'god';
$enteredUserPass = 'qwerty';
$doc = new DOMDocument();
$doc->loadXML($xmlStr);
$selector = new DOMXpath($doc);
//the quote styles are important below
$result = $selector->query("/employees/employee/access_info[username='$enteredUsername']/password");
//if length should happen to be longer than 1, well you screwed up long
//time ago by allowing multiple same usernames, and that can't be allowed!
//if length is 0, then there is no such username
if ($result->length === 0) {
die('NO SUCH USERNAME EXISTS');
} elseif ($result->length > 1) {
die('ERROR: CONSULT ADMIN');
}
//ok, now we know $result->length is 1
$password = $result->item(0)->nodeValue;
if ($password == $enteredUserPass) {
echo 'The password matches! logging in....';
//now we might want some other info about the employee
$employee = $result->item(0)->parentNode->parentNode;
//just demoing showing the employee
echo '<br><br>'.htmlentities($doc->saveXML($employee));
}
?>