Search through XML using PHP [duplicate]

Let me start by restating your question as I understood it: If you have several children of the server-element, which themselves each have a child identified by ip addresses, how could you pull out the username and password for a given ip address?

If that was indeed your question, I believe the solution below could work for you:


// Declare which ip address you want to get more information about
$ip_address_to_find = '';

// Full xml string that you need to search through (this is an imagined example. The last element in this xml is the one we're going to find)
$xml_string = '
             <ipaddress name="">
             <ipaddress name="">
             <ipaddress name="">
             <ipaddress name="">
             <ipaddress name="">

// Use simplexml to make an object out of it
$xml_object = simplexml_load_string($xml_string);

// Cycle through the object until you find a match
foreach($xml_object as $server){
    if($server->ipaddress->attributes()->name == $ip_address_to_find ){
        $username = $server->ipaddress->username;
        $password = $server->ipaddress->password;
        // Now use $username and $password however you want
        // for example:
        echo 'For the server with IP address: '.$ip_address_to_find.', the username is: '.$username.', and the password is: '.$password.'.'.PHP_EOL;

Browse More Popular Posts

Leave a Comment