Wednesday, 20 January 2016

XML : Trouble loading SimpleXML object for use in foreach loop : Warning: Invalid argument supplied for foreach()

I'm trying to load a simple XML object from file using simplexml_load_file(); I've been scraping around the internet trying to get a handle on an error with with the subsequent foreach loop. However depending on which SimpleXML method is used the error has also been an I/O file read error, and also the infamous :

  Parse error: syntax error, unexpected T_FOREACH in SERVER_PATH on line 646    Or : Warning: Invalid argument supplied for foreach() in SERVER_PATH on line 648    

I believe the cause of this is still the XML object failing to load.

At some point I even get an error for a non-existant unexpected closing bracket (depending on which simpleXML obj method is used :

  Parse error: syntax error, unexpected '}' in D:\Hosting\7074516\html\StoneOak\index.php on line 658    

Anyway this is my code:

  <?php      $feed = file_get_contents('ABSOLUTE_URL');      $items = simplexml_load_string($feed);            foreach ($items->parent->review as $review) {  //Error_line    echo "<div class='review_strip_single'>" . PHP_EOL;          echo $review->location . " - " . $review->date . PHP_EOL;              echo "<img src='img/avatar1.jpg' alt='' class='img-circle'>" . PHP_EOL;          echo "<p>" . $review->quote . "</p>" . PHP_EOL;              echo "</div><!-- End review strip -->" . PHP_EOL;          }  ?>    

Some people mention not using HTTP (as this can be blocked by server settings), or that preparing a string for the memory control abstraction can help :

  //$feed = file_get_contents('ABSOLUTE_URL');  //$items = simplexml_load_string($feed);        

Somebody else mentioned some people may have a PHP version that doesn't support anonymous functions. Is it ever necessary to prepare a new array() or new SimpleXMLElement()

If I use var_dump($xml), as is suggested when a foreach argument is failing for an apparent lack of an array, I get a really huge string of info but it is loaded all the way to the end of the XML file. Not sure how to read it for success but the ID on child elements seems to progress naturally except for string.

No comments:

Post a Comment