简体   繁体   中英

How to search for certain name in XML with PHP

I want to be able to go trough the each of the nodes in XML and when I find a certain username I want to read all the data from that node.

For example:

<Users>
   <User>
      <Username>admin</Username>
      <Server>10.x.x.x</Server>
   </User>
   <User>
      <Username>test</Username>
      <Server>11.x.x.x</Server>
   </User>
</Users>

I need to be able to find Username=admin and then get the Server from the same node. I will be using a PHP and you can make example with saving in any two variables.

Using Xpath and DomDocument , something like this should do the trick :

$doc = new DOMDocument;
$doc->loadXML($xml); // Your xml string
$xpath = new DOMXpath($doc);

$query = '//Users/User/Username[. = "admin"]'; // Looking for user admin
$entries = $xpath->query($query);

foreach ($entries as $entry) {
    //Getting the "server" node value for "admin" user
    echo $entry->nextSibling->nextSibling->nodeValue; // Display 10.x.x.x
}

This variant works

$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadXML(file_get_contents('xpath.xml'));
$xpath = new DOMXPath($dom);
$query = '//Users/User/Username[text()="admin"]/following-sibling::Server';
echo $xpath->query($query)->item(0)->nodeValue;

try something along these lines:

$input = '<Users>
   <User>
      <Username>admin</Username>
      <Server>10.x.x.x</Server>
   </User>
   <User>
      <Username>test</Username>
      <Server>11.x.x.x</Server>
   </User>
</Users>';

$xml = new SimpleXMLElement($input);

$result = $xml->xpath('/Users/User[Username="admin"]');
// Process $result to your liking..

For simplicity I've used SimpleXMLElement. If you require more powerful tools, have a look at DomDocument and DOMXPath .

More details regarding SimpleXML Xpath .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM