Возникают проблемы с получением правильной идеи - PullRequest
0 голосов
/ 10 мая 2011

Хорошо, я пишу php-код для редактирования тегов и данных внутри этих тегов, но у меня большие проблемы, пытаясь разобраться в этом.

В основном у меня есть XML-файл, похожий на этот, но больше

<users>
 <user1>
  <password></password>
  </user1>
</users>

и php-код, который я использую, чтобы попытаться изменить тег user1, это

function mod_user() {
    // Get global Variables
    global $access_level;

    // Pull the data from the form
    $entered_new_username = $_POST['mod_user_new_username'];
    $entered_pass = $_POST['mod_user_new_password'];
    $entered_confirm_pass = $_POST['mod_user_confirm_new_password'];
    $entered_new_roll = $_POST['mod_user_new_roll'];
    $entered_new_access_level = $_POST['mod_user_new_access_level'];

    // Grab the old username from the last page as well so we know who we are looking for
    $current_username = $_POST['mod_user_old_username'];

    // !!-------- First thing is first. we need to run checks to make sure that this operation can be completed ----------------!!

    //  Check to see if the user exist. we just use the normal phaser since we are only reading and it's much easier to make loop through
    $xml = simplexml_load_file('../users/users.xml');

    // read the xml file find the user to be modified
    foreach ($xml->children() as $xml_user_get)
    {
        $xml_user = ($xml_user_get->getName());

        if ($xml_user == $entered_new_username){
            // Set array to send data back
            //$a = array ("error"=>103, "entered_user"=>$new_user, "entered_roll"=>$new_roll, "entered_access"=>$new_access_level);

            // Add to session to be sent back to other page
            // $_SESSION['add_error'] = $a;
            die("Username Already exist - Pass");
            // header('location: ../admin.php?page=usermanage&task=adduser');
        }
    }

    // Check the passwords and make sure they match
    if ($entered_pass == $entered_confirm_pass) {
        // Encrypt the new password and unset the old password variables so they don't stay in memory un-encrytped
        $new_password = hash('sha512', $entered_pass);

        unset ($entered_pass, $entered_confirm_pass, $_POST['mod_user_new_password'], $_POST['mod_user_confirm_pass']);
    }

    else {

        die("passwords did not match - Pass");
    }

    if ($entered_new_access_level != "") {
        if ($entered_new_access_level < $access_level){
            die("Access level is not sufficiant to grant access - Pass");
        }
    }

    // Now to load up the xml file and commit changes.
    $doc = new DOMDocument;
    $doc->formatOutput = true;
    $doc->perserveWhiteSpace = false;
    $doc->load('../users/users.xml');

    $old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0);

    // For initial debugging - to be deleted
    if ($old_user == $current_username)
        echo    "old username found and matches";

    // Check the variables to see if there is something to change in the data.
    if ($entered_new_username != "") {
        $xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($entered_new_username, $old_user);

        echo "Username is now: " . $current_username;
    }

    if ($new_pass != "") {
        $current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;

        //$replace_password = $doc
    }
}

при запуске только с именем пользователя, введенным для изменения, я получаю эту ошибку

Catchable fatal error: Argument 1 passed to DOMNode::replaceChild() must be an instance of DOMNode, string given, called in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 252 and defined in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 201

может кто-нибудь объяснить мне, как это сделать, или показать мне, как они это сделают ... для меня может иметь смысл понять, как это делается: s

спасибо

Ответы [ 2 ]

1 голос
/ 10 мая 2011

$entered_new_username - строка, поэтому вам нужно обернуть ее объектом DOM, например, $doc->createElement()

    $xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($doc->createElement($entered_new_username), $old_user);

Возможно, это не совсем правильно, но, надеюсь, это укажет вам правильное направление.

0 голосов
/ 11 мая 2011

хорошо, что он записал и заменил нужный мне узел, но я столкнулся с другими проблемами, с которыми мне нужно разобраться (IE: это замена всего дерева, а не просто изменение имени узла)код, который я использовал,

    // For initial debugging - to be deleted
if ($old_user == $current_username)
    echo    "old username found and matches";

// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
    try {
    $new_node_name = $doc->createElement($entered_new_username);

    $old_user->parentNode->replaceChild($new_node_name, $old_user);
    }
    catch (DOMException $e) {
        echo $e;
    }
    echo "Username is now: " . $current_username;
}

if ($new_pass != "") {
    $current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;

    //$replace_password = $doc
}

$doc->save('../users/users.xml');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...