Search code examples
phpsimplexml

Selecting a PHP SimpleXML object element that is a number


I am unsure how to select the "code" element - the script below is not working.

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

I tried using: $timingCode = (string) $reply->timing->code['0']->attributes()->value;

As well as: $timingCode = (string) $reply->timing->code{'0'}->attributes()->value;

Original XML below:

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


Solution

  • I worked around this by using json_decode then json_encode however it feels "hacky" to me so if others might suggest a better approach - have at it.

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

    Another option using a modification of @Xorifelse answer looks like this:

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

    This works as well: $med_order_data['timingCode'] = (string) $reply->timing->code->code->text['value'];