I use dom parser to grab text from two html documents with the same li class and I retrieved a double value.
<?php
include_once('simple_html_dom.php');
$links = array (
"Model_one" => "car.html",
"Model_two" => "car/edition.html"
);
foreach ($links as $key=>$link) {
$html = file_get_html($link);
$ret[] = $html->find('ul li[class=dotCar]',0)->plaintext;
$pattern = '/.\d+(?:\.\d{2})?((?<=[0-9])(?= usd))/';
preg_match_all($pattern, $ret[0], $result);
$price = array();
foreach($result[0] as $k=>$v) {
$price[] = $v;
echo $price[0];
}
}
// $price[0]= 10.55 11
?>
How can I associate the model_key from $links array to value $price to obtain the result:
model_one 10.55
model_two 11.00
In this way I can retrieve the single value to insert in a MySQL table.
Perhaps something like this:
foreach($result as $k=>$v) {
//$v is the price (10.55 etc.)
foreach($links as $kk=>$vv) {
//$vv is the link (model_one etc.)
$priceAndLinks[$vv] = $v;
}
}
This might give you an idea of the logic needed.
Related
I Want To Get ID From Link i have set all links in array and explode forward slash / and then loop it but i'm getting only one id main link in array
"/4tzCuIpHHhc/long-title-here", i need this id 4tzCuIpHHhc
i'm trying this
<?php
$links = array(
"/WSNINQJZj1s/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-run-nam-joo-hyuk-errand-20161130",
"/Nmy5FWgX0S0/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuk-reject-a-proposal-20161130",
"/u3gumA7-38A/weightlifting-fairy-kim-bok-ju-ep05-did-you-fall-in-love-with-my-brother-20161130",
"/Zsa_saeRT1E/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-offered-joo-hyuk-a-deal-20161130",
"/9q0uUfSr0lE/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuks-angry-at-lee-sung-kyung-20161130",
"/UH6YqMDdMDE/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-and-lee-jae-yoons-drive-date-20161130",
"/5pC2NJtCg_I/weightlifting-fairy-kim-bok-ju-ep03-did-you-fight-because-of-me-20161123",
"/UbxbVugdIdo/weightlifting-fairy-kim-bok-ju-ep01-lee-sung-kyung-fell-into-the-pool-20161116",
"/f29SpSqcOQc/weightlifting-fairy-kim-bok-ju-ep03-lee-sung-kyung-got-into-trouble-20161123",
"/ydWm_Pnp1BQ/weightlifting-fairy-kim-bok-ju-ep04-lee-sung-kyung-vs-nam-joo-hyuk-20161124",
"/uiLlQSexJr4/weightlifting-fairy-kim-bok-ju-ep01-an-underwear-thiefs-identity-20161116",
"/4tzCuIpHHhc/weightlifting-fairy-kim-bok-ju-ep01-weightlifter-vs-rhythmic-gymnast-20161116",
"/QzRi9_4-ItQ/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-enter-a-contest-instead20161130",
);
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s = $explode_c[1];
}
echo $s;
?>
Make $s as array
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s[] = $explode_c[1];
}
print_r($s);
You can do like this, replace your with below:
$links = array(
"/WSNINQJZj1s/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-run-nam-joo-hyuk-errand-20161130",
"/Nmy5FWgX0S0/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuk-reject-a-proposal-20161130",
"/u3gumA7-38A/weightlifting-fairy-kim-bok-ju-ep05-did-you-fall-in-love-with-my-brother-20161130",
"/Zsa_saeRT1E/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-offered-joo-hyuk-a-deal-20161130",
"/9q0uUfSr0lE/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuks-angry-at-lee-sung-kyung-20161130",
"/UH6YqMDdMDE/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-and-lee-jae-yoons-drive-date-20161130",
"/5pC2NJtCg_I/weightlifting-fairy-kim-bok-ju-ep03-did-you-fight-because-of-me-20161123",
"/UbxbVugdIdo/weightlifting-fairy-kim-bok-ju-ep01-lee-sung-kyung-fell-into-the-pool-20161116",
"/f29SpSqcOQc/weightlifting-fairy-kim-bok-ju-ep03-lee-sung-kyung-got-into-trouble-20161123",
"/ydWm_Pnp1BQ/weightlifting-fairy-kim-bok-ju-ep04-lee-sung-kyung-vs-nam-joo-hyuk-20161124",
"/uiLlQSexJr4/weightlifting-fairy-kim-bok-ju-ep01-an-underwear-thiefs-identity-20161116",
"/4tzCuIpHHhc/weightlifting-fairy-kim-bok-ju-ep01-weightlifter-vs-rhythmic-gymnast-20161116",
"/QzRi9_4-ItQ/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-enter-a-contest-instead20161130",
);
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s[] = $explode_c[1]; // made array of exploded string
}
echo "<pre>";
print_r($s);
$result = array_search('4tzCuIpHHhc', $s); // search for the string if you need key from $s
echo $id = $s[11];// $result = 11
*
What I want is, for the DOM to instead of printing the results line by line in a "foreach" loop, rather store it in an array.... So it should look like a list i.e.
"[0] 16GB USB Stick" "[1] Computer monitor" "[2] wireless keyboard"
etc etc
So far I have this, but it only stores the last value from the for each loop.. Please help!
*
$html = new DOMDocument();
#$html->loadHtmlFile('some online shop');
$xpath = new DOMXPath($html);
$nodelist = $xpath->query( "//div[#class='productname']/p" );
foreach ($nodelist as $n)
{
$value = $n->nodeValue;
$list = array($value);
}
echo $list[0];
That's because you're overriding it in each loop. Create an array, and add to that array:
$list = array();
foreach ($nodelist as $n)
{
$value = $n->nodeValue;
$list[] = $value;
}
// Check there's at least one item in the array before accessing it
if (count($list) > 0)
{
echo $list[0];
}
You need to look into how arrays work in PHP. What you're doing wrong is you are re-declaring the array on each iteration, instead of adding more information to it.
$list = array();
foreach ($nodelist as $n) {
$list[] = $n->nodeValue;
}
var_dump($list);
Explanation:
[] basically means - add an item in this array, and auto generate the key.
The foreach I wrote is equivalent to this one:
$i = 0;
foreach ($nodelist as $n) {
$list[$i] = $n->nodeValue;
$i ++;
}
I have a string I would like to separate and make a multidimensional array out of. The string looks like this:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
Unfortunately, I have no control over how the string is put together, which is why I'm trying to make this array.
My goal is to make an array like this:
$item[1]['color'] // = blue
$item[2]['material'] // = silk
So, here's what I've done:
$item = array();
$i=0; // I know this is messy
$eachitem = explode("item-",$string);
array_shift($eachitem); // get rid of the first empty item
foreach ($eachitem as $values) {
$i++; // Again, very messy
$eachvalue = explode(",",$values);
array_pop($eachvalue); // get rid of the last comma before each new item
foreach ($eachvalue as $key => $value) {
$item[$i][$key] = $value;
}
}
I'm obviously lost with this... any suggestions?
You're mostly there. Just replace your inner foreach with
foreach ($eachvalue as $value) {
$properties = explode(':', $value);
$item[$i][$properties[0]] = $properties[1];
}
You're close, this is how I would do it:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$substr = explode("item-", $string);
$items = array();
foreach ($substr as $string) {
$subitems = array();
$pairs = explode(",", $string);
foreach ($pairs as $pair) {
list($key, $value) = explode(":", $pair, 2);
$subitems[$key] = $value;
}
$items[] = $subitems;
}
var_dump($items);
Using list here is great :) Do note that you would need the extra count limiter in explode else you might lose data if there are more :.
$array = array();
$string = explode(',', $string);
foreach($string as $part):
$part = trim($part);
if(strlen($part) < 3) continue;
$part = explode(':', $part);
$array[$part[0]] = $part[1];
endforeach;
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$num_attr = 3;
$item = array();
$i=$x=0;
foreach(explode(',', trim($string,',')) as $attr)
{
list($key, $value) = explode(':', $attr);
$item[$x+=($i%$num_attr==0?1:0)][$key] = $value;
$i++;
}
Set the $num_attr to the number of item attributes in the string (this will allow adjustments in the future if they grow/shrink). The trim inside the foreach is removing ay "empty" data like the last comma (it will also remove a empty first comma if one ever shows up). The crazy looking $item[$x+=($i%$num_attr==0?1:0)] is taking the modulus of the counter / number of attributes which when it is 0 that means we are on a new product line so we add 1 to x which populates the item number index, if the modulus returns a number then we know we are on the same product so we add 0 which doesn't change the items index so that attribute is added on to the same item.
I am trying to display the posts of some RSS Feeds and I came up with a question/problem I have, when I have two same feeds I am trying to show not all the posts but the unique. What I was using is this, that shows me all the posts twice (this is logical)
<?php
$feeds = array(
'feed.xml', 'feed.xml'
);
// Get all feed entries
$entries = array();
foreach ($feeds as $feed) {
$xml = simplexml_load_file($feed);
$entries = array_merge($entries, $xml->xpath('/rss/channel//item'));
}
// Sort feed entries by pubDate (ascending)
usort($entries, 'mysort');
function mysort($x, $y) {
return strtotime($y->pubDate) - strtotime($x->pubDate);
}
foreach ($entries as $entry) {
echo $entry->title;
echo "<br>";
}
?>
but when I changed that line to
$entries = array_unique(array_merge($entries, $xml->xpath('/rss/channel//item')));
I get only one post shown.
How can I correctly show the posts only once? Thank you.
Update:
function mysort($x, $y) {
return strtotime($y->pubDate) - strtotime($x->pubDate);
}
$feeds = array( 'http://feeds.bbci.co.uk/news/world/rss.xml',
'http://feeds.bbci.co.uk/news/world/rss.xml'
);
// Get all feed entries
$entries = array();
foreach ($feeds as $feed) {
$xml = simplexml_load_file($feed);
$entries = array_merge($entries, $xml->xpath('/rss/channel//item'));
}
$uniqueEntries = array();
foreach ($entries as $entry) {
$uniqueEntries[(string)$entry->title] = $entry;
}
// Sort feed entries by pubDate (ascending)
usort($entries, 'mysort');
foreach ($uniqueEntries as $entry) {
echo $entry->title;
echo "<br>";
}
From the documentation of array_unique
Note: Two elements are considered equal if and only if (string) $elem1
=== (string) $elem2. In words: when the string representation is the same. The first element will be used.
In this case, the objects you're getting out of the XPath query translate to string form like "SimpleXML object" (not exactly like that, but the exact representation is not important). According to the above rules, then, every element looks exactly the same to array_unique.
Unfortunately, there's no way to make array_unique behave the way you want, so you will need to fake it yourself:
$feeds = array(
'myfeed.xml', 'myfeed.xml'
);
// Get all feed entries
$entries = array();
foreach ($feeds as $feed) {
$xml = simplexml_load_file($feed);
$tmp = $xml->xpath('/rss/channel//item');
foreach ($tmp as $item) {
if(!in_array($tmp, $entries)) {
$entries[] = $tmp;
}
}
}
I'm not sure if this will work, as it depends on being able to compare objects, and also I don't know that identical nodes from separate XML documents would compare the same anyway. But try it, and let me know. I can whip something else up if this doesn't work.
I have an XPath query that gets Genres of a movie.
$genreXpath = $xml_data->xpath("//category");
I get the attributes from $genreXpath like this
$genreName=array();
$genresID=array();
$i=0;
foreach($genreXpath as $node) {
$genre = $node->attributes();
$genreName[$i] = $node["name"];
$genresID[$i] = $node["id"];
$i++;
}
I'm going to be writing these values to a Db hence the two different arrays.
This code works but I know there has to be a better way of doing this be it with a 2 d array, not using a $i counter or something more obvious that I haven't figured out....any pointers???
foreach($genreXpath as $i=>$node) { //note $i is your index of the current $node
$genre = $node->attributes();
$genreName[$i] = $node["name"];
$genresID[$i] = $node["id"];
}
It auto increments and you do not need to declare it above.
Use foreach($genreXpath as $key => $node) {
If you looking to a multidimensional you could do:
$genres = array();
foreach($genreXpath as $node) {
$genre = $node->attributes();
$genres[] = array($node["name"], $node["id"]);
}