【发布时间】:2019-12-26 03:07:50
【问题描述】:
我正在处理一个在 PHP 中使用 SimpleXML 的页面。这是我的想法,但如果有更好的方法,我愿意接受,因为我从 PHP 中的 XML 开始。
第一步是过滤<record>节点并将其设置为等于某个变量。
接下来,计算<congrant> 子节点的数量,其中<status> 子节点的值为“funded”,并将该值设置为等于某个变量。
最后,使用 For 循环,并从上面插入 count 变量,循环遍历那些 <congrant> 子节点并显示“状态”子节点的值。
我遇到的问题是在 For 循环中。我收到此错误:
Notice: Trying to get property of non-object
因为这将与使用 For 循环的分页代码一起使用,如下所示:
for ($i = $offset; $i < ($offset + $per_page); $i++)
我认为,我需要将它与 For 循环一起保存。感谢您提供任何线索。
这是我的 XML(“test.xml”):
<?xml version="1.0" encoding="utf-8"?>
<data>
<record id="1A">
<congrant>
<ident>a</ident>
<status>Not Funded</status>
</congrant>
<congrant>
<ident>b</ident>
<status>Funded</status>
</congrant>
<congrant>
<ident>c</ident>
<status/>
</congrant>
</record>
<record id="1B">
<congrant>
<ident>a</ident>
<status>Not Funded</status>
</congrant>
<congrant>
<ident>b</ident>
<status>Funded</status>
</congrant>
<congrant>
<ident>c</ident>
<status/>
</congrant>
</record>
<record id="1C">
<congrant>
<ident>aaa</ident>
<status>Funded</status>
</congrant>
<congrant>
<ident>bbb</ident>
<status>Funded</status>
</congrant>
<congrant>
<ident>c</ident>
<status>Funded</status>
</congrant>
</record>
</data>
这是我的 PHP:
//get xml
$url_bio = "test.xml";
$xml_bio = simplexml_load_file($url_bio);
//get count of congrant status 'funded' within the selected 'record' node ('1A')
$xml_bio_record=$xml_bio->xpath('//record[@id="1A"]');
$total_funded_count = 0;
foreach($xml_bio_record as $xb){
$xb_funded_count = count($xb->xpath('./congrant[status="Funded"]'));
echo('<br>$xb_funded_count for this record is...'.$xb_funded_count);
$total_funded_count += $xb_funded_count;
}
//loop and display congrant status
for ($i = 0; $i <= $xb_funded_count; $i++){
echo('<br>'.$i.'<br>');
$strStatus[$i]=$xml_bio_record->congrant->status;
//$strStatus=(string)$congrant->status;
//echo $xml_bio_record->xpath('./congrant/status');
//echo "<br>$strStatus is... {$xml_bio_record->congrant->status[$i]}";
echo('<br>$strStatus is...'.$strStatus[$i]);
}
【问题讨论】:
-
您希望从中得到什么输出?目前尚不清楚您要做什么。