I am working on a code which is giving me an output source of URL. Then when I have this output, I parse an javascript text. Here is the text which I am parsing: http://pastebin.com/7yZ9RqJa
Here is my code:
<?PHP
$url = 'http://www.sportsdirect.com/dunlop-mens-canvas-low-top-trainers-246046?colcode=24604622';
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);
$DataVariants = $xpath->query('//span[@class="ImgButWrap"]/@data-variants')->item(0)->nodeValue;
$jsonStart = strpos($DataVariants, '[');
$jsonEnd = strrpos($DataVariants, ']');
$collections = json_decode(substr($DataVariants, $jsonStart, $jsonEnd - $jsonStart + 1));
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
$SizeNames = $item->SizeVariants->SizeName;
echo "$ColVarId - $SizeNames ,<br>";
}
?>
This is giving me the result like:
24604603 - ,
24604684 - ,
24604640 - ,
24604609 - ,
24604682 - ,
24604686 - ,
24604681 - ,
24604689 - ,
24604602 - ,
24604679 - ,
24604680 - ,
24604622 - ,
24604685 - ,
24604683 - ,
24604621 - ,
24604677 - ,
24604688 - ,
So with this code I used to get all the ColVarId
s. In addition to that I want to get all SizeName
for a specific ColVarId
.
For example I want to get all SizeName
ids for ColVarId
= 24604603 .
Is it possible and how I can make that ?
Thanks in advance!
You can modify your loop to read size names to next:
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
$SizeNames = [];
foreach ($item->SizeVariants as $size) {
$SizeNames[] = $size->SizeName;
}
$names = implode(',', $SizeNames);
echo "$ColVarId - $names ,<br>";
}
Also I think before add $size->SizeName value to $SizeNames array better test if it is real/not empty size.
SizeVariants is also an array, so you cannot access SizeName property of the array, you have to specify which element of that array you want to get SizeName.
$SizeNames = $item->SizeVariants
foreach ($SizeNamesas $sn)
{
echo $sn->SizeName;
}
This is how you access the SizeName. If you want to access all SizeNames of a specific ColVarId, you can check that inside your foreach.
$myColVarId = 24604603;
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
if($ColVarId == $myColVarId){
$SizeNames = $item->SizeVariants
foreach ($SizeNamesas $sn)
{
echo "$ColVarId".'-'.$sn->SizeName;
}
}
else
continue; //this item does not have our ColVarId, so we skip.
}
$SizeNames = $item->SizeVariants->SizeName;
echo "$ColVarId - $SizeNames ,<br>";
}
The code is not tested.