Search code examples
phpxmlsimplexml

Getting info from a specific XML Node


I am trying to read the value for 3 specific XML nodes (bill_codes, sent_total, clicked_unique_total) I have done a lot of testing and I feel like I need someone with fresh eyes to look at this and help me find out what I no longer see..

I am using the simplexml_load_string function to load the XML into an array..

Here is the code that I have so far:

$xml = simplexml_load_string($content);
echo $xml->methodResponse->item->responseData->message_data->message->bill_codes;

This is the XML that I am using (comes from an API Call so I have no access to modifying/updating the structure of the XML)

<?xml version="1.0" encoding="utf-8"?>
<methodResponse>
  <item>
    <methodName>
      <![CDATA[legacy.message_stats]]>
    </methodName>
    <responseData>
      <message_data>
        <message id="2345456">
          <message_subject>
            <![CDATA[#1 Item You Should Be Hoarding in 2015]]>
          </message_subject>
          <date_sent>2014-12-18 04:01:34</date_sent>
          <message_notes>
            <![CDATA[Sample Notes]]>
          </message_notes>
          <withheld_total>0</withheld_total>
          <globally_suppressed>0</globally_suppressed>
          <suppressed_total>0</suppressed_total>
          <bill_codes>
            <![CDATA[8578]]>
          </bill_codes>
          <sent_total>734273</sent_total>
          <link_append_statement/>
          <timezone/>
          <message_name>
            <![CDATA[Sample Message Name]]>
          </message_name>
          <optout_total>4054</optout_total>
          <optout_rate_total>0.55</optout_rate_total>
          <clicked_total>5363</clicked_total>
          <clicked_unique>4350</clicked_unique>
          <clicked_rate_unique>13.71</clicked_rate_unique>
          <campaign_id>228640</campaign_id>
          <campaign_type>C</campaign_type>
          <included_groups>
            <segment id="1208891">
              <![CDATA[Segment Name Here]]>
            </segment>
          </included_groups>
          <included_smartlists></included_smartlists>
          <excluded_groups></excluded_groups>
          <excluded_smartlists></excluded_smartlists>
          <attributes></attributes>
          <link id="40278272">
            <has_name>1</has_name>
            <clicked_unique_total>4350</clicked_unique_total>
          </link>
        </message>
      </message_data>
    </responseData>
    <responseNum>
      <![CDATA[1]]>
    </responseNum>
    <responseCode>
      <![CDATA[201]]>
    </responseCode>
  </item>
</methodResponse>

Solution

  • No need to include the parent, just start with the ->item:

    echo $xml->item->responseData->message_data->message->bill_codes;
    

    Sample Output