从 PHP 中的 XML 中从 <p> 标记中获取值


Get value from <p> tag from XML in PHP

我有一个XML,我想在PHP中检索<p>标签中的值。我该怎么做?我正在尝试getElementbyIdgetAttribute但我无法获取数据。

$xmlDoc = new DOMDocument();$path_to_dir = "/var/www/html/Dalai/Annotation/0001.xml";
$xmlDoc->load($path_to_dir);$elements1 = $xmlDoc->getElementsByTagName('text');
foreach($elements1 as $node)
{
    foreach($node->childNodes as $child) 
    {
       if($child->nodeName=='p')
       {
        $path=$child->getAttribute();
        echo $path;
       }
    }
}
我认为

在这一行中$path=$child->getAttribute(); getAttribute 应该将一个字符串作为参数,然后返回一个字符串。

假设 <p> 中的值是指文本内容,例如 <p>foo</p> 中的 foo ,那么您可以通过 textContentnodeValue * 访问它:

$path = $child->textContent;
//or $path = $child->nodeValue;
echo $path;

*) 任何一个都可以,因为在这种情况下,它将在DOMElement上调用。有关textContentnodeValue之间更细微的区别,请参阅:PHP DOM textContent vs nodeValue?