代码之家  ›  专栏  ›  技术社区  ›  DropHit

选择一个php simplexml对象元素,它是一个数字

  •  0
  • DropHit  · 技术社区  · 6 年前

    我不确定如何选择“code”元素-下面的脚本不起作用。

    $reply = SimpleXMLElement Object(
     [timing] => SimpleXMLElement Object(
       [code] => SimpleXMLElement Object(
         [0] => SimpleXMLElement Object (
           [@attributes] => Array (
             [value] => q6h PRN
           )
         )
       )
     )
    

    我试着用: $timingCode = (string) $reply->timing->code['0']->attributes()->value;

    以及: $timingCode = (string) $reply->timing->code{'0'}->attributes()->value;

    原始XML如下:

    <Bundle xmlns="http://hl7.org/fhir"><timing><code><text value="q6h PRN" /></code></timing></Bundle>

    3 回复  |  直到 6 年前
        1
  •  1
  •   Xorifelse    6 年前

    使用XML解析器怎么样?

    $str = '<Bundle xmlns="http://hl7.org/fhir"><timing><code><text value="q6h PRN" /></code></timing></Bundle>';
    $xml = simplexml_load_string($str);
    
    foreach($xml->timing->code->text[0]->attributes() as $a => $b) {
      echo "my key is '$a' and the value is '$b'";
    }
    

    但由于它是一个单一的值:

    echo $xml->timing->code->text[0]->attributes(); // echo the value of the first attribute of text, can be used in iteration.
    echo $xml->timing->code->text['value'];         // This uses the first element found and gets the value attribute.
    echo $xml->timing->code->text[0]['value'];      // This uses the first element found and make sure the first "text" element is used to get the value attribute from.
    

    也就足够了。

        2
  •  0
  •   DropHit    6 年前

    我通过使用json_decode然后使用json_encode解决了这个问题,但是我觉得它“有点老套”,所以如果其他人可能建议更好的方法的话,请尝试一下。

    $get_timing_code = json_decode(json_encode($reply->timing->code), true);
    $med_order_data['timingCode'] = $get_timing_code['0']['0']['@attributes']['value'];
    

    使用@xorifelse answer修改的另一个选项如下所示:

    $med_order_data['timingCode'] = (string) $reply->timing->code->text[0]->attributes()->value;

    这同样有效: $med_order_data['timingCode'] = (string) $reply->timing->code->code->text['value'];

        3
  •  0
  •   IMSoP    6 年前

    如果XML是按写的:

    <Bundle xmlns="http://hl7.org/fhir">
        <timing>
            <code>
                <text value="q6h PRN" />
            </code>
        </timing>
    </Bundle>
    

    那么你的第一次尝试已经接近了,但是你缺少了 text 节点,所以它需要:

    $timingCode = (string) $reply->timing->code[0]->text->attributes()->value;
    

    请注意 code[0] 意思是“第一个元素 <code> ,所以你可以同样地写:

    $timingCode = (string) $reply->timing[0]->code[0]->text[0]->attributes()->value;
    

    如果不给出数字,simplexml将假定第一个节点,因此即使有多个节点,也可以编写:

    $timingCode = (string) $reply->timing->code->text->attributes()->value;
    

    更简单地说,如果不处理名称空间,通常不需要 ->attributes() 方法,只使用数组键语法访问属性,因此本例中最简单的形式实际上是:

    $timingCode = (string) $reply->timing->code->text['value'];