PHP DOMElement::getElementsByTagName - Anyway to get just the immediate matching children?

后端 未结 4 468
感动是毒
感动是毒 2020-12-16 03:08

is there a way to retrieve only the immediate children found by a call to DOMElement::getElementsByTagName? For example, I have an XML document that has a category element.

4条回答
  •  天涯浪人
    2020-12-16 03:36

    Something like this should do

    /**
     * Traverse an elements children and collect those nodes that
     * have the tagname specified in $tagName. Non-recursive
     *
     * @param DOMElement $element
     * @param string $tagName
     * @return array
     */
    function getImmediateChildrenByTagName(DOMElement $element, $tagName)
    {
        $result = array();
        foreach($element->childNodes as $child)
        {
            if($child instanceof DOMElement && $child->tagName == $tagName)
            {
                $result[] = $child;
            }
        }
        return $result;
    }
    

    edit: added instanceof DOMElement check

提交回复
热议问题