0

I have an XML file that I need to loop through and check for a string match. Not sure why the code below isn't working, i.e. does not return "true".

XML

<AUTHORIZED>
<USER>janedoe</USER>
<USER>sallysmith</USER>
<USER>walterwilliams</USER>
<USER>jennyjones</USER>
</AUTHORIZED>

PHP

<?php

    $user = 'janedoe';

    //Load xml file
    if (file_exists('users.xml')) {
        $authUsers = simplexml_load_file('users.xml');
    } else {
        echo 'Could not find list of authorized users!';
    }

    //Check for approved user
    if(in_array($user, $authUsers)){
        $approvedUser = 'true';
    } else {
        $approvedUser = 'false';
    }

    echo $approvedUser;

?>
2
  • Please do a var_dump on $approvedUser. I don't think it is structured like you think it is. Commented Aug 12, 2016 at 19:50
  • var_dump($approvedUser) yields: string(5) "false" Commented Aug 12, 2016 at 19:55

1 Answer 1

2

The function simplexml_load_file returns a SimpleXMLElement and not an Array, so you can't use the in_array function to do this.

What you can do, is take the value if $authUsers->USER (which is also a SimpleXMLElement), convert it to array, and then check it:

$str = "<AUTHORIZED>
<USER>janedoe</USER>
<USER>sallysmith</USER>
<USER>walterwilliams</USER>
<USER>jennyjones</USER>
</AUTHORIZED>";


$user = 'janedoe';

$authUsers = simplexml_load_string($str);
var_dump((array) $authUsers->USER);

//Check for approved user
if(in_array($user, (array) $authUsers->USER)){
    $approvedUser = 'true';
} else {
    $approvedUser = 'false';
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this did what I needed.
You are welcome. A vote up for the answer will also be appreciated :)
Sorry about that. Done :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.