Jump to content

XML: how to select by values in attributes?


Nico7430

Recommended Posts

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?

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);
    // ...
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.