-1

I'm trying to get content from an XML document using PHP.

This is my current code to get regular XML elements (title and URL).

$xml = simplexml_load_file("courses.xml") or die("Error: Cannot create object");
        $i = 0;
        do {
            echo $xml->channel->item[$i]->title.", <a href='";  
            echo $xml->channel->item[$i]->guid."'>URL</a><br>";
            $i = $i + 1;
        } while ($i < 47);

Now, in the XML document there's this kind of element:

<course:image-thumbnail>https://www.edx.org/image.png</course:image-thumbnail>

I tried calling the content of this element using PHP the same way I called the previous elements, but it does not seem to work because of the presencey of the colon : .

How can I make this work?

I've started on PHP and XML only 2 days ago, so it's all really new for me.

Thanks for your help.

  • Look for the `xmlns:course` namespace definition (looks like an attribute). The value is the actual namespace. `course` is only an alias for to make the XML easier to read/write for humans. Several of the SimpleXML methods allow you to provide the namespace as an argument and you can register you own alias for Xpath expressions. – ThW Jan 11 '18 at 09:43
  • Duplicate is the first Google hit for “simplexml_load_file namespaces” - so next time please make that minimal research effort upfront & before asking, thank you. – CBroe Jan 11 '18 at 09:53
  • Meh, who cares. – Niels Coolen Jan 12 '18 at 10:05

1 Answers1

0

Not sure where your image-thumbnail element resides, but you can access it something like this:

$xml->children('courses', true)->{'image-thumbnail'}[0];

The brackets ->{''} are required in case a certain node contains illegal PHP variable characters (like a hpyhen in this case).

silkfire
  • 24,585
  • 15
  • 82
  • 105