2017-08-07 2 views
0

so in meinem Beispiel PHP-Skript Ich habeLaden xml aus einer Datei mit php

$get = file_get_contents('some-book/book.xml'); 
$arr = simplexml_load_string($get);?> 
echo $arr->title; 
echo "<br>"; 
echo $arr->year; 
echo "<br>"; 

ich (wie erwartet)

Some Book Title 
2012 

jetzt das Problem ist, wenn ich versuche, eine XML zu laden in Eine foreach, die XML wird nicht geladen.

$dir = "."; 
$exclude = array(".","..",".*","*.php"); 
if (is_dir($dir)) { 
    $files = array_diff(scandir($dir), $exclude); 
    foreach ($files as $file) : ?> 

     <?php 
      $filepath = str_replace(' ', '%20', $file); 
      $get = file_get_contents($filepath.'/'.$filepath.'.xml'); 
      $arr = simplexml_load_string($get); 
      print_r($arr); 
     ?> 

     <li class="list-group-item"> 
      <div class="col-xs-4 col-sm-3"> 
       <img src="<?= $filepath ?>/folder.jpg" alt="<?= $file ?>" class="img-responsive" /> 
        </div> 
        <div class="col-xs-8 col-sm-9"> 
         <a href="<?= $file ?>"> 
          <?php echo $arr->title; ?> 
         </a> 
        </div> 
        <div class="clearfix"></div> 
       </li> 

     <?php $arr = ''?> 

    <?php endforeach; 
} 

wird diese Linie sollte die xml

$get = file_get_contents($filepath.'/'.$filepath.'.xml'); 

und diese Linie Echo aus den XML-Daten auf den Buchtitel

<?php echo $arr->title; ?> 
+0

Sie kennen diese Zeile nicht? '. Sollte mit Semikolon enden (;). Also ' ' ' – Yolo

+0

danke, aber das Problem nicht behoben. XML wird immer noch nicht mit dem angegebenen Pfad geladen – dreadycarpenter

+0

@Yolo Semikolon ist optional, da es die letzte Zeile ist! –

Antwort

0

Beide file_get_contents und simplexml_load_string kehrt boolean false auf sollte laden Fehler. Ich würde empfehlen, einige defensive Checks hinzuzufügen, um herauszufinden, was genau falsch läuft.

$get = file_get_contents($filepath.'/'.$filepath.'.xml'); 
if ($get === false) { 
    echo 'failed to read ' . $filepath . '/' . $filepath . '.xml <br>'; 
    var_dump(file_exists($filepath.'/'.$filepath.'.xml')); 
    // if file_exists returns true, check the file permissions 
    continue; 
} 

$arr = simplexml_load_string($get); 
if ($arr === false) { 
    echo 'check if ' . $filepath . ' contains valid xml <br>'; 
    continue; 
}