Jump to content

XML: how to select by values in attributes?


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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.