2012-04-17 49 views
1

我有一个小问题。我需要解析一个文件并用结果填充Web横幅。问题是,文件名为:“_banner_products.php”,它的内容如下:解析带.php扩展名和php头的xml文件

<?php header('Content-Type:text/xml'); ?><?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?> 
<carouselle> 
<firstLayer> 
    <layerName>Leica Disto X310</layerName> 
    <layerProduct>Disto X310</layerProduct> 
    <layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic> 
    <layerPrice>0,-</layerPrice> 
    <layerPriceOld></layerPriceOld> 
    <layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink> 
    <layerTimer>01.05.2012 00:00</layerTimer> 
</firstLayer> 
<firstLayer> 
    ..... 
    ..... 
</firstLayer> 
</carouselle> 

我怎样才能通过这个文件组中的所有“firstLayer”孩子培养成一个等.. 环如果我只是用:

$file = fopen("_banner_products.php", "r"); 
while (!feof($file)){ 
    $line = fgets($file); 
} 

使用simplexml_load_file抛出这个 - “_banner_products.php:1:分析器错误:开始标记预期, '<'”

然后我只得到<的内容。 ..>标记意味着如果我已经超出范围,那么我就无法区分。

感谢任何人的回应。如果有什么不清楚的地方,我会尽力解释更多。

编辑。 谢谢你的解决方案,确实使用完整的URL工作:

simplexml_load_file("http://localhost/MySite/_banner_products.php"); 

回答

2

你有问题,因为simplexml_load_file的治疗您的文件中像本地XML文件..你需要做的就是添加完整URL

simplexml_load_file("http://localhost/web/_banner_products.php"); 

使用案例越来越layerName例如

什么

_banner_products.php

<?php 
header ('Content-Type:text/xml'); 
echo '<?xml version="1.0" encoding="UTF-8"?>'; 
?> 
<carouselle> 
<firstLayer> 
    <layerName>Leica Disto X310</layerName> 
    <layerProduct>Disto X310</layerProduct> 
    <layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic> 
    <layerPrice>0,-</layerPrice> 
    <layerPriceOld></layerPriceOld> 
    <layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink> 
    <layerTimer>01.05.2012 00:00</layerTimer> 
</firstLayer> 
<firstLayer> 
    <layerName>Leica Disto X310</layerName> 
    <layerProduct>Disto X310</layerProduct> 
    <layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic> 
    <layerPrice>0,-</layerPrice> 
    <layerPriceOld></layerPriceOld> 
    <layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink> 
    <layerTimer>01.05.2012 00:00</layerTimer> 
</firstLayer> 
</carouselle> 

查看详情

$xml = simplexml_load_file("http://localhost/lab/stockoverflow/_banner_products.php"); 

echo "<pre>" ; 
foreach($xml as $key => $element) 
{ 
    echo $element->layerName , PHP_EOL ; 
} 
+1

除此之外,遍历你应该使用类似http://www.php.net/manual/en/simplexml.examples-的例子#4码的XML basic.php – Bendihossan 2012-04-17 13:17:24

+0

如果我把完整路径 'http:// localhost/MySite/_banner_products.php' 它给我 'I/O警告:未能加载外部实体“/_banner_products.php”' – JoonasL 2012-04-17 13:26:20

+0

它应该工作,如果你把它@JoonasL – Baba 2012-04-17 13:27:24

1

最明显的方式做到这一点是去掉第一行,并与您的代码添加XML声明回去。

你也可以用解析PHP文件,使用eval(),但要非常不确定您解析什么,因为这可能是一个非常大的安全漏洞。