我想从元素id
的{{1}}属性创建一个数组,但是下面的代码返回所有XML。
PHP文件:
<b>
XML文件(已修复):
$xmlfile=simplexml_load_file("test.xml");
$test=$xmlfile->xpath("/a//b[@id]");
答案 0 :(得分:2)
Hello_ mate
如果我理解你,这段代码将完成这项工作:
解决方案1
$xmlfile = simplexml_load_file("test.xml");
$items = $xmlfile->xpath("/a//b[@id]");
$result = array();
foreach ($items as $item) {
$result[] = $item['id']->__toString();
}
echo '<pre>' . print_r($result, true) . '</pre>';
exit;
// Output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
解决方案2
$sampleHtml = file_get_contents("test.xml");
$result = array();
$dom = new \DOMDocument();
if ($dom->loadHTML($sampleHtml)) {
$bElements = $dom->getElementsByTagName('b');
foreach ($bElements as $b) {
$result[] = $b->getAttribute('id');
}
} else {
echo 'Error';
}
echo '<pre>' . print_r($result, true) . '</pre>';
exit;
// Output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
答案 1 :(得分:1)
如果您只想从let hero: Hero = {
id: 1,
name: 'windstorm'
};
代码中提取id
个属性值,请尝试以下<b>
:
XPath
因为/a/b/@id
表示提取所有/a//b[@id]
个b
属性且id
的后代
答案 2 :(得分:0)
我觉得现有的答案都告诉你一半你需要知道的事情。
首先,您的XPath是错误的:b[@id]
表示“任何具有属性ID的b元素”。您需要b/@id
,意思是“任何id属性,它是b元素的子元素。”
其次,SimpleXML xpath
方法返回表示匹配的元素或属性的SimpleXMLElement
个对象数组。要获取这些属性的文本内容,您需要使用(string)$foo
将每个属性转换为字符串。
所以:
$xmlfile = simplexml_load_file("test.xml");
$test = $xmlfile->xpath("/a//b/@id");
$list = [];
foreach ( $test as $attr ) {
$list[] = (string)$attr;
}