2015-10-13 67 views
0

我有一个XML文件中设置像这样PHP DOMXpath未定义的变量错误

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

我试图XPath来从一个元素中提取属性,使用元素“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); 

如果任何人都可以帮助我,或者至少让我指向正确的方向,我会非常感激。

回答

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" 
}