如何使用 PHP simpleXML 解析特定的 xml 文件
我知道已经有很多关于 simpleXML 和 PHP 的主题,但我需要有关特定 xml 代码的帮助。
<vitrine>
<canal>Hotwords</canal>
<product id="0">
<descricao>MP3 Apple iPod Class...</descricao>
<loja>ApetreXo.com</loja>
<preco>à vista R$765,22</preco>
<urlImagem>http://imagem.domain.com.br/thumbs/ensopado/18/80x80_107156_1.jpg</urlImagem>
<urlProduto>http://domain.com.br/tr/rd?o=BiY4C2UnHQ0LOWgyGjc3NRFp-</urlProduto>
</product>
<product id="1">
<descricao>TV Sony Bravia 3D LE...</descricao>
<loja>Fast Shop.com.b...</loja>
<preco>10 x R$299,90</preco>
<urlImagem>http://imagem.domain.com.br/thumbs/ensopado/2852/80x80_319373_1.jpg</urlImagem>
<urlProduto>http://domain.com.br/tr/rd?o=JDEn-</urlProduto>
</product>
</vitrine>
我需要一个 foreach 来从每个“产品”获取数据,如下所示:
<?
$feedUrl = 'url to xml file';
$rawFeed = file_get_contents($feedUrl);
$xml = simplexml_load_string($rawFeed);
foreach ($item ...????? ?)
{
}
我怎样才能执行此 foreach 来获取数据。我尝试了我所知道的一切,但没有成功。
谢谢。
I know there is already a lot of topics about simpleXML and PHP, but I need help with an specific xml code.
<vitrine>
<canal>Hotwords</canal>
<product id="0">
<descricao>MP3 Apple iPod Class...</descricao>
<loja>ApetreXo.com</loja>
<preco>à vista R$765,22</preco>
<urlImagem>http://imagem.domain.com.br/thumbs/ensopado/18/80x80_107156_1.jpg</urlImagem>
<urlProduto>http://domain.com.br/tr/rd?o=BiY4C2UnHQ0LOWgyGjc3NRFp-</urlProduto>
</product>
<product id="1">
<descricao>TV Sony Bravia 3D LE...</descricao>
<loja>Fast Shop.com.b...</loja>
<preco>10 x R$299,90</preco>
<urlImagem>http://imagem.domain.com.br/thumbs/ensopado/2852/80x80_319373_1.jpg</urlImagem>
<urlProduto>http://domain.com.br/tr/rd?o=JDEn-</urlProduto>
</product>
</vitrine>
I need a foreach to get the data from each "product" like this:
<?
$feedUrl = 'url to xml file';
$rawFeed = file_get_contents($feedUrl);
$xml = simplexml_load_string($rawFeed);
foreach ($item ...????? ?)
{
}
How can I do this foreach to get the data. I tried all that I know without success.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您需要
作为 XML 中的第一行,否则无效。然后,这将帮助您在编码生涯中调试各种事情,请尝试这一行:
这将为您提供从
simplexml_load_string()
调用返回的对象的确切布局。从那里,由于您可以看到对象布局,因此您应该能够弄清楚如何解析它。顺便说一句,就你的情况而言,我认为你需要做类似的事情:First, you need
<?xml version="1.0" encoding="UTF-8"?>
as the first line in your XML, otherwise it's not valid. Then, and this will help you debug all sorts of things over your coding career, try this line:That will give you the exact layout of the object you get back from the
simplexml_load_string()
call. From there, since you have a visual of the object layout, you should be able to figure out how to parse it. Incidentally, in your case, I think you'd need to do something like:PHP 似乎去掉了空格后的所有内容,因为
product id
已更改为product
。无论如何,这是代码。输出
It seems PHP gets rid of evrything after the whitespace, because
product id
was changed to justproduct
. Anyway here's the code.Outputs