简体   繁体   中英

simple xml problem with xml stand alone tags

<field name="first_name" type="text">
        <label>First Name</label>
        <constraints>
            <required />
            <min_length>1</min_length>
            <max_length>255</max_length>
        </constraints>
     </field>
    <field name="password" type="password">
        <label>Password</label>
        <constraints>
            <required />
            <min_length>6</min_length>
            <max_length>8</max_length>
        </constraints>
    </field>
    <field name="age" type="text">
        <label>Age</label>
        <constraints>
            <min>1</min>
            <max>99</max>
        </constraints>
     </field>

assume that i have this xml how do i check required filed existence in each items .

i have this code

$i=0 ;
    foreach($xml as $field) 
        {

                $required = $xml->field[$i]->constraints[0]->required ; 
                var_dump($required) ; 

            $i++ ; 
        } 

if you see var_dump result you'll get the problem here is var_dump result :

object(SimpleXMLElement)#4 (0) {}
object(SimpleXMLElement)#2 (0) {}
object(SimpleXMLElement)#5 (0) {}

there is no required tag in third field segment but var_dump result is same .

You can use this code:

$i = 0;
foreach ($xml as $field) {
    if (isset($field->constraints->required))
        echo "Field $i constraints include a `required` element.\n";
    else
        echo "Field $i constraints do not include a `required` element.\n";
    ++$i;
}

which outputs:

Field 0 constraints include a `required` element.
Field 1 constraints include a `required` element.
Field 2 constraints do not include a `required` element.

The tag has no body, therefore you should use isset, like this:

<?php

$s = '<?xml version="1.0"?>
<data>
  <field name="first_name" type="text">
    <label>First Name</label>
    <constraints>
      <required />
      <min_length>1</min_length>
      <max_length>255</max_length>
    </constraints>
  </field>
  <field name="password" type="password">
    <label>Password</label>
    <constraints>
      <required />
      <min_length>6</min_length>
      <max_length>8</max_length>
    </constraints>
  </field>
  <field name="age" type="text">
    <label>Age</label>
    <constraints>
      <min>1</min>
      <max>99</max>
    </constraints>
  </field>
</data>';

foreach (simplexml_load_string($s) as $i => $field) {
    printf("Is field %d required: %b\n", $i, isset($field->constraints[0]->required));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM