0

Trying to count if a name is present in the XML file and how many times, can anybody help? I'm already on version 35 with internet code I've tried but mostly it only counts the tags instead of the content between the tags.

<?php

$xml = <<< XML
<Book>
<Contact>
        <Name>An Smith</Name>
</Contact>
    <Contact>
        <Name>Alex Pepper</Name>
</Contact>
    <Contact>
        <Name>Tom James</Name>
</Contact>
;
</Book>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

// to detect, count if variable NameToFind is present
$NameToFind="Alex Pepper";

// Missing code 

echo "$NameToFind is x times present in the XML ";

Done some attemps with all your comments and finally this was the working code I needed:

$xml=simplexml_load_file('book.xml'); 
$nodes= $xml->xpath("//Book/Contact[contains(.,'$NameToFind')]");
$count = count($nodes);
Kevin
  • 1
  • 1

3 Answers3

0

Probably something like this:

$xpath = new DOMXPath($dom);
$query = '//Book/Contact/Name[. = "' . $NameToFind . '"]';
$entries = $xpath->query($query);
$count = count($entries);

Although my xpath query may be a little off.

pritaeas
  • 2,073
  • 5
  • 34
  • 51
0

I think this is what you are after.

https://stackoverflow.com/a/10162624/736639

Another option would be to convert the XML to an array using xml2array library: http://www.bin-co.com/php/scripts/xml2array/.

$array = xml2array($xmlstring);
Community
  • 1
  • 1
karmafunk
  • 1,453
  • 12
  • 20
0
$xml=simplexml_load_file('book.xml'); 
$nodes= $xml->xpath("//Book/Contact[contains(.,'$NameToFind')]");
$count = count($nodes);
Kevin
  • 1
  • 1