1

I tried to search the web for any good samples but I don´t get them to work with my xml feed.

I´m parsing this file https://www.kursadmin.org/pls/kas/sf_fu.create_web_cdata_xml but it will only return the first field.

The feed is a list of courses and I would like to parse out a list of all cours titles and IDs.

This is what I got so far but it only parse out the first course (KURS).

$xml=simplexml_load_file("https://www.kursadmin.org/pls/kas/sf_fu.create_web_cdata_xml");

foreach($xml as $x) {
 echo $x->KURS->KURS_NAVN . "<br><br>";
}

Any great suggestions - all new to this kind of parsing?

0

2 Answers 2

1

You need to add one more foreach to loop and traverse for all KURS object

<?php
$xml=simplexml_load_file("https://www.kursadmin.org/pls/kas/sf_fu.create_web_cdata_xml");

foreach($xml as $x) {
    foreach($x->KURS as $y){
        echo $y->KURS_NAVN . "<br><br>";
    }
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thaks! :) As simple as that.
0

You fell into the trap of SimpleXMLs automatic mapping. You iterate the child elements of the document element. This is the ReportArea inside the Report element node. You iterate this single element and access the first KURS and the first KUR_NAVN element inside it.

Use DOM+Xpath to fetch data from an XML. This is more like using SQL for an database.

// create the DOM and load the XML
$dom = new DOMDocument();
$dom->load('https://www.kursadmin.org/pls/kas/sf_fu.create_web_cdata_xml');

// create an Xpath object an register a prefix for the namespace
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('cr', 'urn:crystal-reports:schemas');

// fetch the KURS_NAVN nodes and output them
foreach ($xpath->evaluate('//cr:KURS/cr:KURS_NAVN') as $node) {
  echo $node->nodeValue . "<br>\n";
}

Output:

Spesialpedagogisk assistent- Mosjøen<br>
Spanskkurs nybegynner del 1+2 (A1), intensiv - Oslo<br>
Datakurs: Data grunnkurs - nybegynnere<br>
Norsk litt øvet (A2) - Eid<br>
Norskkurs mellomnivå del B (B1) - Bergen (1231)<br>
Sykurs: For det meste - helg<br>
Franskkurs nybegynner del 2, A1 - Biri<br>
...

Or, you can iterate the KURS element nodes and use them as an context for additional expressions.

foreach ($xpath->evaluate('//cr:KURS') as $node) {
  echo $xpath->evaluate('string(cr:KURS_NAVN)', $node) . "<br>\n";
}

Comments

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.