Nico7430 Posted February 8, 2011 Share Posted February 8, 2011 Hi I want to select certain elements of an xml-file by value of attributes. Take for example: <?xml version="1.0" encoding="UTF-8"?> <data> <Report ID="3"> <Date>REVIEW</Date> <AuthorID>3b</AuthorID> </Report> <Report ID="2"> <Date>REVIEW</Date> <AuthorID>2a</AuthorID> </Report> </data> Now I want all the information (elements, data, etc) associated with attributes ID that have the value "3". I tried the following code: <?php $xmlDoc = new SimpleXMLElement('data.xml', null, true); $var = $xmlDoc->Report['ID']; if ($var = "not") { echo "ID = yes"; } else { echo "not"; } ?> However, it always shows "yes", whatever value I add for $var in the if-statement. I have the impression that it produces a boolean value based on the question if there is an ID-attribute at all. But how do I access the value that is inside as a criteria to select with? Quote Link to comment https://forums.phpfreaks.com/topic/227083-xml-how-to-select-by-values-in-attributes/ Share on other sites More sharing options...
Nico7430 Posted February 10, 2011 Author Share Posted February 10, 2011 Ah, I need to change the line: if ($var = "not") { in: if ($var == "not") { Great! Quote Link to comment https://forums.phpfreaks.com/topic/227083-xml-how-to-select-by-values-in-attributes/#findComment-1172189 Share on other sites More sharing options...
requinix Posted February 10, 2011 Share Posted February 10, 2011 Your code merely gets the first Report. That's different from getting the one with id=3. $reports = $xml->xpath("/data/Report[@id=3]"); if (count($reports) == 0) { // not found } else { $report = current($report); // ... } Quote Link to comment https://forums.phpfreaks.com/topic/227083-xml-how-to-select-by-values-in-attributes/#findComment-1172202 Share on other sites More sharing options...
Nico7430 Posted February 14, 2011 Author Share Posted February 14, 2011 Mmm, I have to agree that things did not work as I expected. But the code to use the value of an attribute looks like: $reports = $xml->xpath("/data/Report[@id=3]"); Nice. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/227083-xml-how-to-select-by-values-in-attributes/#findComment-1173946 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.