2017-08-07 47 views
0

所以在我的示例PHP腳本我有加載XML與PHP

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

我得到(預期)

Some Book Title 
2012 

現在的問題是,當我嘗試加載XML中一個foreach,xml不加載。

$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; 
} 

這條線應該加載XML

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

和這條線應該呼應從XML數據

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

不知道這行''??php $ arr =''?>'。應以分號(;)結尾。所以'<?php $ arr =''; ?>' ' – Yolo

+0

謝謝,但沒有解決問題。仍然不提供路徑提供的xml – dreadycarpenter

+0

@Yolo分號是可選的,因爲它是最後一行! –

回答

0

兩個file_get_contentssimplexml_load_string書名將返回布爾值false上失敗。我建議增加一些防禦性檢查來找出究竟發生了什麼問題。

$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; 
}