0

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?

2 Answers 2

1

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

}
Sign up to request clarification or add additional context in comments.

6 Comments

eheh sorry, i was not so clear, i check if it exist already on that server this is a sort of "sync" of two different places, so if something is present in place A must be in B otherwise, i insert it :D
may i ask you why you are testing both isset and empty? does a attribute with an empty value is considered set?
If a key exists in an array, that means it is set. However it could still be an empty value, so if you check both you know the key contains something. Hope this helps.
@DanielWade: This is SimpleXMLElement so not an array (just ArrayAccess). Also isset(expr) && !empty(expr) can be written as just !empty(expr). see php.net/empty ; php.net/isset
@Hakre, fair comment. I thought it generated an E_WARNING if you checked !empty on something that didn't exist.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.