PHP |如何查找 xml 给定内容的标签名称

PHP | how to find tag name of given content of xml

我想构建这样的函数:

function getTagNameOfGivenContent($content){...}

这是 xml 的示例:

<w:r>
    <w:rPr>
        <w:rFonts w:cs="Arial" />
        <w:sz w:val="18" />
        <w:szCs w:val="18" />
    </w:rPr>
    <w:t>tfInvLineTaxCode</w:t>
</w:r>

所以当我这样调用函数时

getTagNameOfGivenContent('tfInvLineTaxCode')

会return

<w:t>tfInvLineTaxCode</w:t>

谁能告诉我如何构建这个函数?

也许是这样的:

$dom = new \DOMDocument();

$dom->loadXML($xml_doc);

$script = $dom->getElementsByTagName('script');

更多信息 -> http://php.net/manual/es/class.domdocument.php

希望对您有所帮助。

这是一个解决方案...

  1. 将 XML 加载到 DOMDocument 中,然后 ...
  2. 创建一个 DOMXPath 对象,在其上...
  3. 运行 一个 XPath query to find the first node with matching text 内容。
  4. 如果找到,则返回该节点的标记。如果不是,则返回 null

代码:

$source = <<<EOX
<root xmlns:w="whatever">
    <w:r>
        <w:rPr>
            <w:rFonts w:cs="Arial" />
            <w:sz w:val="18" />
            <w:szCs w:val="18" />
        </w:rPr>
        <w:t>tfInvLineTaxCode</w:t>
    </w:r>
</root>
EOX;

// Create/load a DOMDocument and a DOMXPath instance 
$dom = new DomDocument();
$dom->loadXML($source);
$xpath = new DOMXPath($dom);

function getTagNameOfGivenContent($content)
{
    // Query XPath instance for first node with a text that matches $content
    global $xpath;
    $tags = $xpath->query('//*[text()="' . $content .'"][1]');

    if ($tags->length > 0) {
        // We got a match
        $tag = $tags->item(0);
        return $tag->ownerDocument->saveXML($tag);
    }

    // No match
    return null;
}

// Try it out
echo getTagNameOfGivenContent('tfInvLineTaxCode');

输出:

<w:t>tfInvLineTaxCode</w:t>