0

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"/>
</transcript_list>

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?

Thanks.

4
  • Have a look here How do you parse and process HTML/XML in PHP? Commented Oct 25, 2016 at 1:43
  • Thanks for trying to help, but I already know how to parse it, I just need to know how to loop through getting rest of the lines. Much appreciated. Commented Oct 25, 2016 at 1:48
  • you seams not to know... you speek about a loop but your code seams not to need a loop ... you need to parse the xml as an array then you can work with it as a single array ore multidimensional array in a loop Commented Oct 25, 2016 at 1:50
  • i get the point... working wih arrays will be ok also but you find the way for him ;) Commented Oct 25, 2016 at 1:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that was an amazing, concise and also a very quick answer. This is exactly what I needed, and now I also understand how it works... much appreciated...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.