digitalmads
digitalmads

Reputation: 7

PHP/XML - checking if a node is set

I have an XML document structured like this:

<produkter>
    <produkt>
        <forhandler></forhandler>
        <produktnavn></produktnavn>
        and so on...
    </produkt>
</produkter>

I am pulling out data like this:

$produktnavn = utf8_decode($xmlObject->item($i)->getElementsByTagName('produktnavn')->item(0)->childNodes->item(0)->nodeValue);

Now I am looking to do a check to see if the node is present in the XML document at all.

For example... I only want to make the operation above if there actually IS a node called "produktnavn".

I am trying with:

if (isset($xmlObject->item($i)->forhandler)) {

But this doesn't seem to work.

What an I doing wrong?

Upvotes: 0

Views: 166

Answers (2)

IMSoP
IMSoP

Reputation: 97898

The result of getElementsByTagName is always a DOMNodeList; that class has a member length, described as:

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

So to check if there is at least one item in the list, check that length is > 0:

$produktnavn_nodes = $xmlObject->item($i)->getElementsByTagName('produktnavn');
if ( $produktnavn_nodes->length > 0 ) {
    $produktnavn = utf8_decode($produktnavn_nodes->item(0)->childNodes->item(0)->nodeValue);
    // ... do something with $produktnavn
}

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163457

You could use DOMDocument with DOMXPath and check the length for the xpath expression.

For example:

$source = <<<SOURCE
<produkter>
    <produkt>
        <forhandler></forhandler>
        <produktnavn></produktnavn>
    </produkt>
</produkter>
SOURCE;

$xmlObject = new DOMDocument;
$xmlObject->loadXML($source);
$xpath = new DOMXpath($xmlObject);
$elements = $xpath->query('//produktnavn');
if ($elements->length > 0) {
    // present
}

Upvotes: 1

Related Questions