简体   繁体   English

PHP:如何从此XML获取关联数组?

[英]PHP: How to get an associative array from this XML?

This is my code so far... needless to say, it's not working :( 到目前为止,这是我的代码...不用说,它不起作用:(

$feed = <<< THEXML

<programs>
<program>
<date>2009-04-16</date>
<start_time>17:00</start_time>
<leadtext>hello hello!
</leadtext>
<name>Program 1</name>
<b-line>Comedy</b-line>
<synopsis>Funny stuff
</synopsis>
<url>http://www.domain.tld/program_name</url>
</program>
<programs>
THEXML;


$xml  = (array) simplexml_load_string($feed);

print_r($xml);exit;

Would appreciate any help, have been around the php.net site for hours now and feeling braindead. 希望对您有所帮助,已经在php.net站点上呆了几个小时,并感到脑筋急转弯。

Please note that in the example xml above there is just one 请注意,在上面的示例xml中,只有一个

 <program>...</program>

tag, but in reality I have one or more of them that I need to use. 标签,但实际上我有一个或多个需要使用。 For example 例如

 <programs>
 <program>...</program>
 <program>...</program>
 <program>...</program>
 </programs>

I figured if I can get one to work then I can loop it, but just thought I would explain what I am going for here. 我想如果可以让一个人上班,那么我可以循环它,但只是想我会在这里解释我要做什么。

Thanks in advance! 提前致谢!

Assuming the provider gives you valid XML, then you just have to iterate through the programs and use any information you need off it, like so: 假设提供程序为您提供了有效的XML,那么您只需要遍历程序并使用所需的任何信息即可,例如:

<?php
foreach ( $xml as $node ) {
    echo $node->synopsis;
    //or whatever property you want to access on the SimpleXMLElement Object
}

Since you don't have correct XML (being an unclosed <programs> tag, then you might want to modify your script to correct that error like so: 由于您没有正确的XML(是未封闭的<programs>标记,因此您可能想要修改脚本以更正该错误,如下所示:

$feed = preg_replace('/<programs>$/', '</programs>', trim($feed));

You're missing the end closing tag. 您缺少结束符。

$feed = <<< THEXML

<programs>
<program>
<date>2009-04-16</date>
<start_time>17:00</start_time>
<leadtext>hello hello!
</leadtext>
<name>Program 1</name>
<b-line>Comedy</b-line>
<synopsis>Funny stuff
</synopsis>
<url>http://www.domain.tld/program_name</url>
</program>
</programs> // <========= here
THEXML;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM