George Ortiz
George Ortiz

Reputation: 309

PHP / SimpleXML - Get attribute value based on attribute name

I'm using SimpleXMLElement like so:

$visitor_body = wp_remote_retrieve_body( $url );
$visitor_data = new SimpleXMLElement( $visitor_body );

I have the following XML structure response:

<resultSet>
  <aggregates>
     <metric name="visitDuration" value="488" label="Avg. Visit Duration"/>
     <metric name="uniqueVisitors" value="8" label="Unique Visitors"/>
     <metric name="visits" value="14" label="Visits"/>
     <metric name="pageViews" value="35" label="Page Views"/>
     <metric name="bounceRate" value="0.5" label="Bounce Rate"/>
     <metric name="pagesPerVisit" value="2.5" label="Pages Per Visit"/>
  </aggregates>

I need to get the value for visitDuration uniqueVisitors visits and so on in way that I can use in various places. For instance, within a variable such as:

echo $visitDuration;
echo $uniqueVisitors;

Upvotes: 2

Views: 2139

Answers (1)

LIGHT
LIGHT

Reputation: 5712

http://php.net/manual/en/book.simplexml.php - this page is where you need to research.

or how about this?

http://simplehtmldom.sourceforge.net/

* A HTML DOM parser written in PHP5+ let you manipulate HTML in a very easy way!
* Require PHP 5+.
* Supports invalid HTML.
* Find tags on an HTML page with selectors just like jQuery.
* Extract contents from HTML in a single line.

// Find all visitDuration
foreach($html->find('visitDuration') as $element)
       echo $element->value. '<br>'; // returns 488

// Find all bounceRate
foreach($html->find('bounceRate') as $element)
       echo $element->value. '<br>'; // returns 0.5

Upvotes: 1

Related Questions