PHP / SimpleXML - 根据属性名称获取属性值

时间:2012-11-24 05:20:30

标签: php xml simplexml

我正在使用SimpleXMLElement:

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

我有以下XML结构响应:

<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>

我需要获得visitDuration uniqueVisitors visits等的值,以便我可以在各个地方使用。例如,在变量中,例如:

echo $visitDuration;
echo $uniqueVisitors;

1 个答案:

答案 0 :(得分:1)

http://php.net/manual/en/book.simplexml.php - 此页面是您需要研究的地方。

或者这个怎​​么样?

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