Zoolander
Zoolander

Reputation: 2363

Need help with SimpleXML and retrieving HREF node value

I'm trying to retrieve the the HREF and echo it out using SimpleXML, but I keep getting the error message below.

Warning: Invalid argument supplied for foreach() in ...

<?php

$url = 'file.xml';

foreach(simplexml_load_file($url)->info->content->item as $it) {
    echo $it->site-page-href;
}

?> 

<?xml version="1.0" encoding="utf-8"?>
<info>
    <content>
        <item>
            <site>
                <page>
                    <href>http://domain.com</href>
                </page>
            </site>
        </item>
    </content>
<info>

Can anyone spot the problem?

Upvotes: 0

Views: 774

Answers (2)

brian_d
brian_d

Reputation: 11395

  1. echo $it->site-page-href; should be echo $it->site->page->href;
  2. Your end tag should be </info>
  3. You should not use ->info as you are already at the root element.
    ie.
    simplexml_load_file($url)->content->item not
    simplexml_load_file($url)->info->content->item

Btw, finding all of the href nodes can be achieved more easily if you use xpath.

 $xml = simplexml_load_file($url);
 $href = $xml->xpath(".//href");
 foreach($href as $h) {
    var_dump($h);
 }

Upvotes: 3

GitsD
GitsD

Reputation: 668

Firstly use

echo $it->site->page->href;

instead

echo $it->site-page-href;

and end the <info> tag with </info> in your XML file.

Upvotes: 0

Related Questions