XML-使用php从属性中获取元素子值

XML-使用php从属性中获取元素子值,php,xml,dom,Php,Xml,Dom,我正在使用php解析我的xml文件,我只想从属性中获取元素的子值: <question number="1"> <type>Main</type> </question> <question number="2"> <type>Secondary</type> </question> 使用 请注意,您必须有一个根节点,因此上面假设有一个元素。通常,使用元素的直接路径

我正在使用php解析我的xml文件,我只想从属性中获取元素的子值:

  <question number="1">
    <type>Main</type>
  </question>

  <question number="2">
    <type>Secondary</type>
  </question>
使用

请注意,您必须有一个根节点,因此上面假设有一个
元素。通常,使用元素的直接路径更有效,但您也可以使用
//问题[…
查询文档中任何位置的

如果您想在没有XPath的情况下做到这一点,您可以这样做

foreach ($xmlDoc->getElementsByTagName('question') as $question) {
    if($question->getAttribute('number') === '1') {
        echo $question->getElementsByTagName('type')->item(0)->nodeValue;
        // or
        echo $question->childNodes->item(1)->nodeValue;
    }
}
请注意,当使用
childNodes
且未将
DOMDocument::preserveWhiteSpace
设置为
FALSE
时,任何换行符、制表符和其他空格都将被解析为
DOMText
节点,因此
项(1)
而不是
项(0)
,因为后者是
DOMText
节点

$xp = new DOMXPath($xmlDoc);
echo $xp->evaluate('string(/questions/question[@number=1]/type)'); // Main
foreach ($xmlDoc->getElementsByTagName('question') as $question) {
    if($question->getAttribute('number') === '1') {
        echo $question->getElementsByTagName('type')->item(0)->nodeValue;
        // or
        echo $question->childNodes->item(1)->nodeValue;
    }
}