<?xml version="1.0" encoding="utf-8"?>
<activities>
<activity category="Team">
<date><h4>Date: January 15, 2017</h4></date>
<work>
<li><b>MR X</b> working on X</li>
<li><b>MR Y</b> working on Y</li></li>
<li><b>MR Z</b> working on Z</li></li>
</work>
</activity>
</activities>
以上是XML文件。假设文件名是activities.xml。
以下是PHP代码:
<?php
$xmls=simplexml_load_file("activities.xml") or die("Error: Cannot create object");
foreach ($xmls as $xml) {
echo $xml->date;
echo $xml->work;
}
?>
我希望使用<h4>
代码和<li>
代码及其他代码获取日期和工作详情,以便我可以直接在HTML中使用它们。
有办法吗?
答案 0 :(得分:0)
还有两个额外的</li>
导致解析错误,除了everythinhg似乎对你想要做的事情有好处。这是我获得的对象:
SimpleXMLElement Object
(
[activity] => SimpleXMLElement Object
(
[@attributes] => Array
(
[category] => Team
)
[date] => SimpleXMLElement Object
(
[h4] => Date: January 15, 2017
)
[work] => SimpleXMLElement Object
(
[li] => Array
(
[0] => SimpleXMLElement Object
(
[b] => MR X
)
[1] => SimpleXMLElement Object
(
[b] => MR Y
)
[2] => SimpleXMLElement Object
(
[b] => MR Z
)
)
)
)
)
答案 1 :(得分:0)
if(file_exists('activities.xml')) {
try{
$xml = simplexml_load_file('activities.xml') or die('Can not load');
$date = $xml->{activity}->{date}->{h4};
echo $date.'<br/>';
foreach($xml->{activity}->{work}->{li} as $work){
echo $work->{b};
echo $work.'<br/>';
}
}catch (\Exception $e){
echo $e->getMessage();
}
}
正确的activities.xml文件内容是
<?xml version="1.0" encoding="utf-8"?>
<activities>
<activity category="Team">
<date><h4>Date: January 15, 2017</h4></date>
<work>
<li><b>MR X</b> working on X</li>
<li><b>MR Y</b> working on Y</li>
<li><b>MR Z</b> working on Z</li>
</work>
</activity>
</activities>