Validating XML attribute value

I am exporting data from an XML file to update my database. I use the following loop:

foreach ($xml->removed->idof as $idof) {
  if ($idof > 0) {
    mysql_query("delete from wp_posts WHERE import_id = '$idof'");
    echo $idof;
  }
}

My data structure is as follows:

<removed>
<idof mlssta='4'>0</idof>
<idof mlssta='6'>60370</idof>
<idof mlssta='14'>150370</idof>
<idof mlssta='6'>150671</idof>
...
</removed>

I need to change the condition ifin order to check the attribute value mlstaa, i.e. if ($idof > 0 && mlstaa != 6).

I just don't know how to extract it. Would love your help.

+4
source share
1 answer

Using a variable $xmllooks like it is being loaded using the SimpleXML extension. Suppose it is initialized as follows:

$xml = simplexml_load_file('some-file.xml');

Then you simply retrieve the attributes with attributes()and check to see if the attribute is in the returned array:

foreach ($xml as $idof) {
  $attr = $idof->attributes();
  if ($attr && $attr['mlssta'] != 6) {
    // remove it here
  }
}
+2
source

Source: https://habr.com/ru/post/1657608/


All Articles