1

我有一个小问题。我需要解析一个文件并用结果填充一个网页横幅。问题是,该文件名为:“_banner_products.php”,其内容如下:

<?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");
4

2 回答 2

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 ;
}
于 2012-04-17T13:09:57.540 回答
1

最明显的方法是去掉第一行,然后在代码中重新添加 XML 声明。

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

于 2012-04-17T13:09:35.757 回答