使用php从xml根节点获取属性

时间:2014-07-18 23:43:48

标签: php xml

我需要使用PHP从XML根节点获取属性。我需要从下面的<result>根节点获取总数,开始数和计数数,并在PHP中将它们指定为变量。

Ex.    $total, $start, $count

<result total="26" start="0" count="10">
<job>
<title>
<![CDATA[ Rep-Retail Sales, Orange County ]]>
</title>
<date>2014-07-12T00:56:17Z</date>
<onclick>j2c_view(1451827617,2834554843,611926905)</onclick>
<company>
<![CDATA[ Verizon Wireless ]]>
</company>
<city>Laguna Niguel, CA</city>
<description>

2 个答案:

答案 0 :(得分:0)

您可以使用attributes()方法访问它们。例如:

$xml = simplexml_load_string($xml_string);
$root_attributes = $xml->attributes();
$total = $root_attributes->total;
$start = $root_attributes->start;
$count = $root_attributes->count;

echo "$total, $start, $count"; // 26, 0, 10

答案 1 :(得分:0)

DOM + Xpath适用于此。

$xml = '<result total="26" start="0" count="10"/>';

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

var_dump(
  $total = $xpath->evaluate('number(/*/@total)'),
  $start = $xpath->evaluate('number(/*/@start)'),
  $count = $xpath->evaluate('number(/*/@count)')
);