2017-03-08 40 views
1

我想從元素<b>id屬性創建一個數組,但下面的代碼返回所有的XML。SimpleXML:將XML屬性值添加到數組

PHP文件:

$xmlfile=simplexml_load_file("test.xml"); 
$test=$xmlfile->xpath("https://stackoverflow.com/a//b[@id]"); 

XML文件(固定):

<a> 
    <b id="1"></b> 
    <b id="2"></b> 
    <b id="3"></b> 
    <b id="4"></b> 
    <b id="5"></b> 
</a> 
+0

怎麼長得一模一樣的xml文件?引號之間是否包含屬性值? –

+0

我更正了XML示例並改進了格式,拼寫,標題和主要問題。 – zx485

回答

2

Hello_的後代交配

如果我理解你正確此代碼段將做的工作都b元素:

SOLUTION 1

$xmlfile = simplexml_load_file("test.xml"); 
$items = $xmlfile->xpath("https://stackoverflow.com/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

如果你想從<b>標籤只提取id屬性值,請嘗試以下XPath

/a/b/@id 

/a//b[@id]手段提取有id屬性,是a

0

我覺得同時現有的答案告訴你,你需要知道的一半。

首先,你的XPath是微妙的錯誤:b[@id]的意思是「任何b元素有一個屬性id」。你想改爲b/@id,意思是「任何id屬性是b元素的子元素」。其次,SimpleXML xpath方法返回表示匹配元素或屬性的對象數組。要獲取這些屬性的文本內容,您需要使用(string)$foo將每個屬性轉換爲字符串。

所以:

$xmlfile = simplexml_load_file("test.xml"); 
$test = $xmlfile->xpath("https://stackoverflow.com/a//b/@id"); 
$list = []; 
foreach ($test as $attr) { 
    $list[] = (string)$attr; 
} 

[Live Demo]