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

Asked

Viewed 219 times

2

The.xml data 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 can get the values, for example, of the elements Q1:Browser and Q1:Messagesource

<?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 do I get the prefix value xsi:type of the element Contactdetail?

  • How to get the text of one of the elements Q1: who is among &lt;![CDATA[ ]]&gt;?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.