jjj jjj - 1 year ago 52
PHP Question

PHP: Parsing XML

I have the following XML file:

<transcript_list docid="6678351850933011277">
<track id="1" name="" lang_code="en-GB" lang_original="English (United Kingdom)" lang_translated="English (United Kingdom)" lang_default="true"/>
<track id="2" name="" lang_code="fr" lang_original="Fran├žais" lang_translated="French"/>
<track id="3" name="" lang_code="de" lang_original="Deutsch" lang_translated="German"/>

As of now, this is the code I got so far:

$sxml = simplexml_load_string($xml);

if ($attrs = $sxml->track->attributes()) {

$attrs = $sxml->track->attributes();

//GET lang_code
$language = $attrs["lang_code"];

//GET name
$name = $attrs["name"];

//GET lang_original
$lang_original = $attrs["lang_original"];

//GET lang_translated
$lang_translated = $attrs["lang_translated"];


// ECHO values
echo "Language: ".$language." | Name: ".$name." | Language Original:".$lang_original." | Language Translated: ".$lang_translated;

Above PHP code works just fine for me, but it only prints the first line of the attributes.

How do I do the loop to echo all lines of the XML file?


Answer Source

You need to loop over the tracks.

foreach($sxml->track as $track) {
    if ($attrs = $track->attributes()) {
        $language = $attrs["lang_code"];
        $name = $attrs["name"];
        $lang_original = $attrs["lang_original"];
        $lang_translated = $attrs["lang_translated"];
           echo "Language: ".$language." | Name: ".$name." | Language Original:".$lang_original." | Language Translated: ".$lang_translated . "\n";

Demo: https://eval.in/665762

Also note if ($attrs = $sxml->track->attributes()) { assigns $sxml->track->attributes() to $attrs so you don't need to do that a second time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download