How to parse XML with namespace and prefix in PHP using SimpleXML?

2

The data.xml file:

<?xml version="1.0" encoding="utf-8" ?>
<rsp status="ok">
<ArrayOfContact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Contact>
        <Date xmlns="XYZ.GetContacts.Contact">2015-03-25T15:34:11.917</Date>
        <ContactDetail xmlns:q1="XYZ.GetContacts.Contact.Detail.Chat" xsi:type="q1:Chat" xmlns="XYZ.GetContacts.Contact">
            <q1:Browser>Chrome</q1:Browser>
            <q1:Platform>Windows 7</q1:Platform>
            <q1:Date>25/03/2015 15:34:11</q1:Date>
            <q1:Dialog>
                <q1:Messages>
                    <q1:Message>
                        <q1:Description>&lt;![CDATA[Olá Fulano de Tal, em que posso ajudar?]]&gt;</q1:Description>
                        <q1:MessageSource>AGENT_TO_USER</q1:MessageSource>
                    </q1:Message>
                    <q1:Message>
                        <q1:Description>&lt;![CDATA[kauan]]&gt;</q1:Description>
                        <q1:MessageSource>USER_TO_AGENT</q1:MessageSource>
                    </q1:Message>
                </q1:Messages>
            </q1:Dialog>
        </ContactDetail>
    </Contact>
</ArrayOfContact>
</rsp>

With the PHP script below, I parse the XML file, and I get the values, for example, from the q1: Browser and q1: MessageSource p>

<?php
$file = "dados.xml";
$xml = simplexml_load_file($file);

$namespaces = $xml->ArrayOfContact->Contact->ContactDetail->getNameSpaces(true);
$qN = $xml->ArrayOfContact->Contact->ContactDetail->children($namespaces['q1']);

echo "q1:Browser --->  {$qN->Browser} <br />";
echo "q1:MessageSource ---> {$qN->Dialog->Messages->Message->MessageSource}";
  • How can I get the xsi: type prefix value of the ContactDetail element?

  • How to get the text of one of the q1: Description elements between &lt;![CDATA[ ]]&gt; ?

asked by anonymous 07.07.2015 / 23:23

0 answers