You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP函数应返回DOMElement却始终返回NULL问题排查

函数返回NULL问题排查与修复

我编写了一个接收DOMElement对象的函数,用于查找其后代元素,返回符合需求的DOMElement。这个函数会在遇到包含“Continued”的标签(比如下面XML中的ContinuedSectionSubsection)时被调用,需要返回该标签前一个兄弟节点的最后一个Text类型DOMElement。

目前遇到的问题是:函数内部的var_dump能正常显示传入的DOMElement,但最终返回的$domElement始终为NULL,哪怕不对$domElement做任何检查也会出现这个情况。

XML片段

<Subsection lims:inforce-start-date="2004-08-31" lims:fid="279739" lims:id="279739">
    <MarginalNote lims:inforce-start-date="2004-08-31" lims:fid="279740" lims:id="279740">Tax payable by non-resident persons</MarginalNote>
    <Label>(3)</Label>
    <Text>Where a person who is not taxable under subsection 2(1) for a taxation year</Text>
    <Paragraph lims:inforce-start-date="2004-08-31" lims:fid="279741" lims:id="279741">
        <Label>(a)</Label>
        <Text>was employed in Canada,</Text>
    </Paragraph>
    <Paragraph lims:inforce-start-date="2004-08-31" lims:fid="279742" lims:id="279742">
        <Label>(b)</Label>
        <Text>carried on a business in Canada, or</Text>
    </Paragraph>
    <Paragraph lims:inforce-start-date="2004-08-31" lims:fid="279743" lims:id="279743">
        <Label>(c)</Label>
        <Text>disposed of a taxable Canadian property,</Text>
    </Paragraph>
    <ContinuedSectionSubsection lims:inforce-start-date="2004-08-31" lims:fid="279744" lims:id="279744">
        <Text>at any time in the year or a previous year, an income tax shall be paid, as required by this Act, on the person’s taxable income earned in Canada for the year determined in accordance with Division D.</Text>
    </ContinuedSectionSubsection>
</Subsection>

原函数代码

function untilUHitText($domElement){
    echo "<br>DomElement analyzed: <br>";
    var_dump($domElement);
    if($domElement->tagName == "Text" || $domElement->childElementCount == 0){
        return $domElement;
    } else {
        untilUHitText($domElement->lastElementChild);
    }
}

测试调用代码

$appendHere = untilUHitText($weirdo->previousSibling);
var_dump($appendHere);

问题原因与修复

问题出在递归调用时没有返回递归结果:当进入else分支调用untilUHitText($domElement->lastElementChild)时,没有把这个递归调用的返回值传递回上层函数,导致递归到最后找到目标DOMElement返回时,上层函数没有承接这个值,最终整个函数默认返回NULL。

修改后的函数只需在else分支添加return关键字,把递归调用的结果返回即可:

function untilUHitText($domElement){
    echo "<br>DomElement analyzed: <br>";
    var_dump($domElement);
    if($domElement->tagName == "Text" || $domElement->childElementCount == 0){
        return $domElement;
    } else {
        // 添加return,将递归结果传递回去
        return untilUHitText($domElement->lastElementChild);
    }
}

内容的提问来源于stack exchange,提问作者Gabriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:10:04