2012-04-17 54 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(),但要非常不確定您解析什麼,因爲這可能是一個非常大的安全漏洞。