我有一个这样的XML文件
<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);
如果有人能帮助我,或者至少指给我正确的方向,我将非常感激。
您正在获取子节点(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"
}