xml独立标记的简单xml问题

时间:2011-02-12 16:54:59

标签: php xml

<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>

假设我有这个xml如何检查每个项目中所需的存档。

我有这个代码

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

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

            $i++ ; 
        } 

如果你看到var_dump结果你会得到问题,这是var_dump结果:

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

第三个字段中没有必需的标记,但var_dump结果相同。

2 个答案:

答案 0 :(得分:0)

您可以使用此代码:

$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;
}

输出:

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

答案 1 :(得分:0)

标签没有正文,因此您应该使用isset,如下所示:

<?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));
}