PHP DOMXpath未定义的变量错误

时间:2015-10-13 16:22:29

标签: php dom xpath

我有一个像这样设置的XML文件

<feeds><feed id="">
<headline></headline>
<author></author>
<datetime></datetime>
<link></link>
<description></description>
</feed></feeds>

我正在尝试使用元素“id”从一个元素中提取属性,但我得到每个属性的未定义变量错误。这是我正在尝试使用的当前脚本。

function extractText($tag) {
foreach ($tag as $item) {
  $value = $item->nodeValue;
}
return $value;
}
$doc = new DOMDocument('1.0');
$doc->load("newsfeed/newsfeed.xml");
$id = $_POST['id'];

$domx = new DOMXPath($doc);
$feed = $domx->query("feeds/feed[@id='$id']");
foreach ($feed as $theid) { 
$h_array = $theid->getAttribute('headline');
$headline = extractText($h_array);

$a_array = $theid->getAttribute('author');
$author = extractText($a_array);

$l_array = $theid->getAttribute("link");
$link = extractText($l_array);

$i_array = $theid->getAttribute("image");
$image = extractText($i_array);

$d_array = $theid->getAttribute("description");
$description = extractText($d_array);

$da_array = $theid->getAttribute("datetime");
$datetime = extractText($da_array);

如果有人能帮助我,或者至少指出我正确的方向,我会非常感激。

1 个答案:

答案 0 :(得分:0)

您将子节点(headline,'author',..)作为属性提取。 DOMElement :: getAttribute()将始终返回标量值,即属性节点的值。示例XML中唯一的属性节点是id。因此,您需要按名称获取子节点。

我建议使用DOMXpath::evaluate()。它可以从Xpath表达式返回标量值。

$xpath->evaluate('string(headline)', $feed);

headline将获取具有$feed名称的所有子节点。 Xpath函数string()将第一个节点强制转换为字符串,返回其文本内容或空字符串。

这也适用于复杂的Xpath表达式。因为转换是在Xpath中完成的,所以可以避免许多验证返回值的条件。根据Xpath表达式,您将始终知道是否将获得节点列表或标量。

$xml = <<<'XML'
<feeds>
  <feed id="123">
    <headline>Headline</headline>
    <author>Author</author>
    <datetime>Someday</datetime>
    <link>Url</link>
    <description>Some text</description>
  </feed>
</feeds>
XML;

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);

$id = '123';

$feedList = $xpath->evaluate("/feeds/feed[@id='$id']");
foreach ($feedList as $feed) {
  var_dump(
    [
      'headline' => $xpath->evaluate('string(headline)', $feed),
      'author' => $xpath->evaluate('string(author)', $feed),
      'link' => $xpath->evaluate('string(link)', $feed),
      'image' => $xpath->evaluate('string(image)', $feed),
      'description' => $xpath->evaluate('string(description)', $feed),
      'datetime' => $xpath->evaluate('string(datetime)', $feed),
    ]
  ); 
}

输出:

array(6) {
  ["headline"]=>
  string(8) "Headline"
  ["author"]=>
  string(6) "Author"
  ["link"]=>
  string(3) "Url"
  ["image"]=>
  string(0) ""
  ["description"]=>
  string(9) "Some text"
  ["datetime"]=>
  string(7) "Someday"
}