选择作为数字的 PHP SimpleXML 对象元素

Selecting a PHP SimpleXML object element that is a number

我不确定如何 select "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>

我通过使用 json_decode 然后 json_encode 解决了这个问题,但是我觉得 "hacky" 所以如果其他人可能会提出更好的方法 - 请尝试一下。

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

使用@Xorifelse 答案修改的另一个选项如下所示:

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

这也适用: $med_order_data['timingCode'] = (string) $reply->timing->code->code->text['value'];

仅使用 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.

也足够了。

如果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] 表示 "the first element called <code>",因此您同样可以这样写:

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

简单XML不给数字就假定为第一个节点,所以即使有倍数也可以这样写:

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

更简单地说,如果你不处理命名空间,你通常不需要 ->attributes() 方法,只需使用数组键语法访问属性,所以在这种情况下最简单的形式实际上是:

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