GuestofHonor
GuestofHonor

Reputation: 133

Invalid argument supplied for foreach() in

i keep getting the error for this code even though it works as it should when i run it in browser, but when called by include_once it doesnt work due to the error

    foreach(($hostlist->uploaded) as $uploaded) {
    if (strcmp($uploaded->url,"http://someurl.com/")==0) {
    $host = simplexml_load_file($config['hostlist']);
    unset($host->uploaded->url);
    unset($host->uploaded->pass);
    $host->uploaded->addChild('url',"http://anotherurl.com/");
    $host->uploaded->addChild('pass',"anotherpass");
    $host->uploaded->asXML($config['hostlist']);
    $host->asXML($config['hostlist']);`
    echo "URL Changed to  http://anotherurl.com/";
    }
  }

knowing that the variables are as follows:

$config['hostlist'] = 'xml/host.xml';

$hostlist = simplexml_load_file($config['hostlist']);

and this is a sample of the xml file:

<host> 
 <uploaded>
  <work>yes</work>
  <url>http://someurl.com/</url>
  <pass>pass</pass>
 </uploaded>
</host>

Upvotes: 0

Views: 218

Answers (1)

Prix
Prix

Reputation: 19528

As I had early mentioned via comments, your issue maybe that the file is using a relative path and being accessed via include_once by a script on a different folder, which causes the file path of your XML to be invalid.

Here is a simple example of what may be happening to you.

I have the following folder structure:

root
  - include_folder/
  - include_folder/read_host.php
  - include_folder/xml
  - include_folder/xml/host.xml
  - test_xml.php

When accessing include_folder/read_host.php it reads the file just fine.

This is my read_host.php:

<?php

$config['hostlist'] = 'xml/host.xml';
$hostlist = simplexml_load_file($config['hostlist']);
foreach($hostlist->uploaded as $uploaded)
{
    echo $uploaded->work, "\n";
    echo $uploaded->url, "\n";
    echo $uploaded->pass, "\n";
}

The output:

yes
http://someurl.com/
pass

However if I access from test_xml.php which have the following content:

<?php
include_once('include_folder/read_host.php');
echo "what happens";

It fails with error:

PHP Warning: simplexml_load_file(): I/O warning : failed to load external entity "xml/host.xml" in /home/admin/include_folder/read_host.php on line 4 PHP Notice: Trying to get property of non-object in /home/admin/include_folder/read_host.php on line 5 PHP Warning: Invalid argument supplied for foreach() in /home/admin/include_folder/read_host.php on line 5

what happens

However if I change $config['hostlist'] = 'xml/host.xml'; to the absolute path to the XML file it works just fine and output:

yes
http://someurl.com/
pass
what happens

So in my case the absolute folder was:

$config['hostlist'] = '/home/admin/include_folder/xml/host.xml';

Upvotes: 1

Related Questions