Hasan
Hasan

Reputation: 53

How to read XML Child Node Value in a String using PHP?

I have a String which gets its value dynamically from other server. Value of string is

$xmloutput = '<response uri="/crm/private/xml/Leads/getRecordById">
    <result>
        <Leads>
            <row no="1">
                <FL val="LEADID">131</FL>
                <FL val="SMOWNERID">20001</FL>
                <FL val="Lead Owner"><![CDATA[Aaron]]></FL>
                <FL val="First Name"><![CDATA[Carol]]></FL>
                <FL val="Last Name"><![CDATA[Custer]]></FL>
                <FL val="Email"><![CDATA[[email protected]]]></FL>
            </row>
            <row no="2">
                <FL val="LEADID">2070</FL>
                <FL val="SMOWNERID">20001</FL>
                <FL val="Lead Owner"><![CDATA[Aaron]]></FL>
                <FL val="Last Name"><![CDATA[Florence, SC]]></FL>
            </row>
        </Leads>
    </result>
</response>

My Question is, generally we use $xml = simplexml_load_file("test1.xml"); to load XML files, but here in my requirement it is a String, how can i read this String value and extract the child node and its value? Example:

<FL val="LEADID">131</FL> // its key is LEADID and value is 131
<FL val="First Name"><![CDATA[Carol]]></FL> // its key is First Name and value is Carol

Is there a way to put this into Array? so that its easy for me to print out its node value?

Upvotes: 1

Views: 973

Answers (1)

Mohammad
Mohammad

Reputation: 21489

Use simplexml_load_string() that is for reading xml from string. Then loop through row elements and in loop, loop through FL elements and then get text content and attribute of element.

$xml = simplexml_load_string($string); 
foreach ($xml->Leads->row as $row) {
    foreach ($row->FL as $fl) {
        echo "{$fl} => {$fl['val']}<br>";
    }
}

Upvotes: 2

Related Questions