Skip to content

@hakre /example.php
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
<?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
Something went wrong with that request. Please try again.