0

Using JQuery AJAX, I send HTTP request to PHP back-end and tried to retrieve XML String parsed into JSON using json_encode() function back to the front-end. Some of the XML contains attributes, which show @attributes in the output. Somehow, I tried to console.log() the @attributes but failed. Here is the detail:

  1. In front-end, using JQuery AJAX, I send HTTP request to one of my PHP file.

  2. In back-end PHP, I retrieve data from DB where one of the column contains String of XML.

  3. Then, after retrieving, I used simplexml_load_string() function to convert the String of XML into true XML.

  4. Here is the example of String of XML:

<dsconnector>
    <statement>
        SELECT SUM(a.doc_amt) FROM gl_temp_trx_dt as a INNER JOIN gl_temp_trx_hd as b ON a.gl_hd_unique_id = b.unique_id
    </statement>
    <filter id="company123" range="false">
        <label>Company</label>
        <table>company</table>
        <field>company_code</field>
        <alias>a</alias>
        <desc>company_name</desc>
        <dependee>glacc, glyear, glperiod</dependee>
    </filter>
</dsconnector>

Notice that <filter> has two attributes

  1. After that, I used json_encode() function to output the converted XML

  2. In front-end, I used console.log() function to see what the output looks like, and here is part of the result:

0: {…}
  "@attributes": {…}
     id: "companyFilterId"
     range: "false"
     <prototype>: Object { … }
  alias: "ar"
  dependee: "projectFilterId_0123, phaseFilterId_ABCD, debtorAccFilterId"
  desc: "company_name"
  field: "company_code"
  label: "Company"
  table: "company"
  <prototype>: Object { … }
...
  1. As you can see, the attributes part contains "@". And by using this code to print the result:
...[other AJAX part]...
success: function(data, textStatus, XMLHttpRequest)
         {
               if (data.status==1)
               {
                  console.log(data.result[0].attributes);
               }
                  else if(data.status==0)
               {

               }
         },
...[other AJAX part]...

It will say that that the attributes is undefined.


My question is, how to display the JSON Array that the object named contains "@". Like in this case, it show "@attributes". Thanks in advance.

Nasrul Arif
  • 165
  • 1
  • 12

1 Answers1

1

It's frustrating when APIs do this. You should be able to access it like so:

data.result[0]['@attributes']
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • 1
    Okay, that was easy. It took me ages to figure that out as I been searching for solution in the internet and couldn't found any. Thank you so much @ceejayoz. I will accept this answer after the awaiting time. – Nasrul Arif Oct 16 '19 at 15:06