2017-08-07 125 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; 
}