XmlParser.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\httpclient;
  8. use yii\base\Object;
  9. /**
  10. * XmlParser parses HTTP message content as XML.
  11. *
  12. * @author Paul Klimov <klimov.paul@gmail.com>
  13. * @since 2.0
  14. */
  15. class XmlParser extends Object implements ParserInterface
  16. {
  17. /**
  18. * @inheritdoc
  19. */
  20. public function parse(Response $response)
  21. {
  22. $contentType = $response->getHeaders()->get('content-type', '');
  23. if (preg_match('/charset=(.*)/i', $contentType, $matches)) {
  24. $encoding = $matches[1];
  25. } else {
  26. $encoding = 'UTF-8';
  27. }
  28. $dom = new \DOMDocument('1.0', $encoding);
  29. $dom->loadXML($response->getContent(), LIBXML_NOCDATA);
  30. return $this->convertXmlToArray(simplexml_import_dom($dom->documentElement));
  31. }
  32. /**
  33. * Converts XML document to array.
  34. * @param string|\SimpleXMLElement $xml xml to process.
  35. * @return array XML array representation.
  36. */
  37. protected function convertXmlToArray($xml)
  38. {
  39. if (is_string($xml)) {
  40. $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  41. }
  42. $result = (array) $xml;
  43. foreach ($result as $key => $value) {
  44. if (!is_scalar($value)) {
  45. $result[$key] = $this->convertXmlToArray($value);
  46. }
  47. }
  48. return $result;
  49. }
  50. }