I am new to php and trying to extract data from url using preg_match_all
Problem is the matches are converted to strings and I cannot extract them individually
<?php
$pattern = '/<span class="product".*/i';
$string = file_get_contents('http://www.example.com/');
preg_match_all($pattern, $string, $matches);
echo '<b>preg_match_all()</b>';
echo '<pre>';
echo '<br /><b>Products:</b> ', var_dump($matches);
echo '</pre>';
Returns
preg_match_all()
Products: array(1) {
[0]=> array(7) {
[0] => string(46) "Product 1"
[1] => string(42) "Product 2"
[2] => string(46) "Product 3"
[3] => string(41) "Product 4"
[4] => string(58) "Product 5"
[5] => string(42) "Product 6"
[6] => string(37) "Product 7"
}
}
I am trying to extract 1 item at a time (i.e. separate elements) and place each into own variable if possible. Example: $product1 = "Product 1"
If I try echo $matches[2];
to get Product 3 I get an undefined offset error
EDIT:
With help from this thread: Retrieve data contained a certain span class
Solution:
<?php
$html=file_get_contents('http://www.example.com/');
preg_match_all("/\<span class\=\"products\"\>(.*?)\<\/span\>/",$html,$b);
foreach($b as $key => $value) {
$$key = $value;
}
echo $value[4]; // Returns 4th key, or "Product 5"
Yes I am terrible at formatting code
Les Test Test Test Paul Custom 1986
with Factory Kahler ` If I use ` – Peeping Tom Jul 07 '13 at 20:53