我有一个小问题。我需要解析一个文件并使用结果填充 Web 横幅。问题是,该文件被称为:"_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>
我怎样才能循环访问这个文件,将所有"第一层"子级分组为一个等等。如果我只使用:
$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");
您遇到了问题,因为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 ;
}
最明显的方法是去掉第一行,然后将 XML 声明与代码一起添加回去。
您也可以使用 PHP 解析文件,使用 eval()
,但要非常确定要解析的内容,因为这可能是一个非常大的安全漏洞。