how to test for empty / null values in xml with php

I have a webservice from where I retrieve informations before updating a database.

I have to search for some values before inserting them, if i found them, obviously I will not insert them the xml should be like this:

<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <categories>
    <category id="10" xlink:href="http://www.server.it/B2B/api/categories/10"/>
    </categories>

if it's full, otherwise :

<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<categories>
</categories>
</prestashop>

after retrieve the xml i make :

$resources = $xml->children()->children();


if ($resources->category[@id] == ""){
insert category
}

now, all this code is working perfectly, but I must admit that those =="" is a bit awful, am I testing it in the right way? or is better some other kind of test? like isset, or null or whatever?

Upvotes: 0

Views: 2395

Answers (2)

hakre
hakre

Reputation: 197544

If you want to test if there are any category children in the categories element, you can just test for that:

$category = $xml->categories->category;

The number of those category child-elements can then be retrieved via the count() function:

if ($category->count()) {
    echo "ID: ", $category['id'];
}

alternatively you can just explicitly look for that first element:

$category = $xml->categories->category[0]

The $category variable will be NULL if it does not exists, otherwise it's the XML element:

if ($category = $xml->categories->category[0]) {
    // insert $category
}

Hope this is helpful.

Upvotes: 1

Daniel Wade
Daniel Wade

Reputation: 46

I'm not sure why you would try to insert the category if it's empty but I think this is what you mean:

if(isset($resources->category[@id]) && !empty($resources->category[@id])){

    //insert category

}

Upvotes: 1

Related Questions