Created
November 6, 2011 19:43
-
-
Save hakre/1343367 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$response = <<<RESP | |
<Groups> | |
<Group> | |
<Item> | |
<Description>One Item - Color: Black, Size: 9</Description> | |
</Item> | |
</Group> | |
<Group> | |
<Item> | |
<Description>Two Item - Color: White, Size: 11</Description> | |
</Item> | |
</Group> | |
</Groups> | |
RESP; | |
$xml = simplexml_load_string($response); | |
foreach($xml->xpath('Group/Item') as $i => $item) | |
{ | |
$description = (string) $item->Description; | |
printf("%d: %s\n", $i, $description); | |
$item = new Item($description); | |
var_dump($item->getName(), $item->getProps()); | |
} | |
class Item | |
{ | |
private $name; | |
public function getName() | |
{ | |
return $this->name; | |
} | |
private $props = array(); | |
public function getProps() | |
{ | |
return $this->props; | |
} | |
public function __construct($description) | |
{ | |
$this->initFromText($description); | |
} | |
private function initFromText($description) | |
{ | |
list($this->name, $propText) = explode(' - ', $description, 2) + array('',''); | |
$propToken = '([a-z]+): (.*?)(, |$)'; | |
$offset = 0; | |
while($r = preg_match("~$propToken~i", $propText, $matches, PREG_OFFSET_CAPTURE, $offset)) | |
{ | |
list($full, $name, $value) = $matches; | |
if ($full[1] !== $offset || isset($this->props[$name[0]])) | |
throw new InvalidArgumentException(sprintf('Invalid Description given ("%s").', $description)); | |
$this->props[$name[0]] = $value[0]; | |
$offset += strlen($full[0]); | |
} | |
// all consumed? | |
if (strlen($propText) !== $offset) | |
throw new InvalidArgumentException(sprintf('Invalid Description given ("%s").', $description)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment