2017-09-02 96 views
0

我有一個包含以下HL7信息的文件:PHP字符串轉換爲對象

{ 
    MESSAGE_HEADER: { 
    SENDING_APPLICATION: 'IQCARE', 
    SENDING_FACILITY: '10829', 
    RECEIVING_APPLICATION: 'IL', 
    RECEIVING_FACILITY: '10829', 
    MESSAGE_DATETIME: '20170713110000', 
    SECURITY: '', 
    MESSAGE_TYPE: 'ADT^A04', 
    PROCESSING_ID: 'P' 
    }, 
    PATIENT_IDENTIFICATION: { 
    EXTERNAL_PATIENT_ID: { 
     ID: '110ec58a-a0f2-4ac4-8393-c866d813b8d1', 
     IDENTIFIER_TYPE: 'GODS_NUMBER', 
     ASSIGNING_AUTHORITY: 'MPI' 
    }}} 

我想這個消息轉換成JSON對象,我做了以下內容:

// copy file content into a string var 
     $json_file = file_get_contents("" . getcwd() . "\integration_layer\ADT^A04 - Patient Registration.json"); 
     echo gettype($json_file); 
// convert the string to a json object 
     $jfo = json_decode($json_file); 
// read the title value 
     $title = $jfo->MESSAGE_HEADER->SENDING_APPLICATION; 
// copy the posts array to a php var 
     $posts = $jfo->PATIENT_IDENTIFICATION->EXTERNAL_PATIENT_ID; 
// listing posts 
     foreach ($posts as $post) { 
      echo $post->ID; 
     } 

但我收到以下錯誤:

Severity: Notice 

Message: Trying to get property of non-object 

當我在$ json_file上使用PHP的getype函數時,它是一個字符串文件。 如何將消息轉換爲我自己系統消耗的對象?

+1

你的JSON文件是不是有效的JSON。 JSON密鑰必須是用引號封裝的字符串。 ''SENDING_APPLICATION':'IQCARE'。 – Spectarion

+0

如果JSON字符串正確,那麼'json_decode(...)'會將它轉換爲PHP中的一個對象。 –

回答

0

validate your JSON代碼。

JSON規則

  1. 數據是名稱/值對
  2. 數據由逗號分隔
  3. 大括號持有的對象 - 您的文件不包含任何父對象
  4. 方括號保存數組
  5. 名稱/值對由字段名稱(用雙引號引起來)組成。 - 您的名字字段是不是在雙引號

有效的JSON代碼:

{ 
     "MESSAGE_HEADER": { 
      "SENDING_APPLICATION": "IQCARE", 
      "SENDING_FACILITY": 10829, 
      "RECEIVING_APPLICATION": "IL", 
      "RECEIVING_FACILITY": 10829, 
      "MESSAGE_DATETIME": "20170713110000", 
      "SECURITY": "", 
      "MESSAGE_TYPE": "ADT^A04", 
      "PROCESSING_ID": "P" 
     }, 
     "PATIENT_IDENTIFICATION": { 
      "EXTERNAL_PATIENT_ID": { 
       "ID": "110ec58a-a0f2-4ac4-8393-c866d813b8d1", 
       "IDENTIFIER_TYPE": "GODS_NUMBER", 
       "ASSIGNING_AUTHORITY": "MPI" 
      } 
     } 
    } 

工作PHP例如與有效的JSON代碼:

<?php 

    $json = ' 
     { 
      "MESSAGE_HEADER": { 
       "SENDING_APPLICATION": "IQCARE", 
       "SENDING_FACILITY": 10829, 
       "RECEIVING_APPLICATION": "IL", 
       "RECEIVING_FACILITY": 10829, 
       "MESSAGE_DATETIME": "20170713110000", 
       "SECURITY": "", 
       "MESSAGE_TYPE": "ADT^A04", 
       "PROCESSING_ID": "P" 
      }, 
      "PATIENT_IDENTIFICATION": { 
       "EXTERNAL_PATIENT_ID": { 
        "ID": "110ec58a-a0f2-4ac4-8393-c866d813b8d1", 
        "IDENTIFIER_TYPE": "GODS_NUMBER", 
        "ASSIGNING_AUTHORITY": "MPI" 
       } 
      } 
     } 
    '; 

    $object = json_decode($json); 

    echo $object->MESSAGE_HEADER->SENDING_APPLICATION; 

?>