public
Created

  • Download Gist
example.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
<?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));
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.