-2

I need to get attributes from an XML root node using PHP. I need to get the number from total, start and count from the <result> root node below and assign them as variable in 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>
psubsee2003
  • 8,563
  • 8
  • 61
  • 79

2 Answers2

0

You can use attributes() method to access them. Example:

$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
user1978142
  • 7,946
  • 3
  • 17
  • 20
0

DOM + Xpath works for that.

$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)')
);
ThW
  • 19,120
  • 3
  • 22
  • 44