I am using xpath to retrieve the text value of some links (a) in a given element. I then push the results to an array called $tableau. Everything is working fine :) The thing is, I would like now to retrieve also the href of those links. So have both the text value and the href in my array. The other thing is, I have no idea how to do that. Hope someone can help. Thank you in advance for your replies. Cheers. Marc
$url = 'http://www.somesite.com';
$path = '.../a';
$tableau = array();
$dom = new DOMDocument();
#$dom->loadHTML($url);
$xpath = new DomXPath($dom);
$x = $xpath->query($path);
foreach ($x as $value)
array_push($tableau, $value->nodeValue);
Try this:
foreach ($x as $value)
{
array_push($tableau, $value->nodeValue, $value->getAttribute('href'));
}
you can use an associative array
the code might look like this(not sure abt the syntax though)
arr = [ "1" => [ "text" => "value1" , "href" => "value1"],
"2" => [ "text" => "value2", "href" => "value2"]];
the xpath xpression to retrieve the href of all the anchor tags is something like this
("//a/#href");
// --> select a from all the descendants of the root
a --> select the anchor tag
#href --> select the href of this anchor (# to select attributes)
convert this expression to equivalent PHP code
Thanks to the hints given by javram and vireshad I manage to find the solution. See here below:
$url = 'http://www.somesite.com';
$path = '.../a';
$tableau = array();
$dom = new DOMDocument();
#$dom->loadHTML($url);
$xpath = new DomXPath($dom);
$x = $xpath->query($path);
foreach ($x as $value)
array_push($tableau, array($value->nodeValue, $value->getAttribute('href')));
Related
I have a Laravel array and would like to modify the returned values.
$array = ['hr-34', 've-53', 'dv-65'];
I want to remove everything before the dash and the dash itself and return the following array.
$array = ['34', '53', '65'];
You can do something like this:
foreach ($c as $key => $value) {
$pieces = explode('-', $value);
$array[$key] = $pieces[1];
}
You have used the tag collections. So if it's a collection you can use this function:
$c->map(function ($item) {
return explode('-', $item)[1];
})
Steps to follow:
define blank array $new_array (to fill single value from foreach loop).
get single value using foreach loop.
use strstr for remove everything before dash and remove '-' using str_replace.
fill single value in $new_array.
return $new_array outside foreach loop.
Below is the code -
$array = ['hr-34', 've-53', 'dv-65'];
$new_array = array();
foreach($array as $key=>$result){
$data = str_replace('-', '', strstr($result, '-'));
$new_array[]= $data;
}
print_r($new_array);
That's all!
https://www.php.net/manual/en/function.array-map.php
https://www.php.net/manual/en/function.explode.php
$array = array_map(function ($item) {
return explode('-', $item)[1];
}, $array)
Edit:
As you changed title from array to collection you can use:
https://laravel.com/docs/9.x/collections#method-map
$collection->map(...)
in a similar way to array_map(...)
$array = ['hr-34', 've-53', 'dv-65'];
$array = collect($array)
->map(fn($item) => explode('-', $item)[1])
->all();
/**
* array:3 [
* 0 => "34"
* 1 => "53"
* 2 => "65"
* ]
*/
dd($array);
Here this code in sandbox
you can use regex with preg_replace as :
$new = array_map(function ($item) {
return preg_replace('/^([^-])+-/', '', $item);
}, $array);
result :
array:3 [
0 => "34"
1 => "53"
2 => "65"
]
I am trying to extract all the links from a webpage and put them into an array that I can then compare values with to see if there is a match. The problem that I'm having is I cannot seem to get the values into an array. I am able to see all the links and I see that there is a match with the one I'm trying to compare with but it's not recognizing that it's there. My code is as follows. Any help would be greatly appreciated.
$content = file_get_contents("sample_url");
$content = strip_tags($content, "<a>");
$subString = preg_split("/<\/a>/", $content);
$items = array();
foreach ( $subString as $val ){
if( strpos($val, "<a href=") !== FALSE ) {
$val = preg_replace("/.*<a\s+href=\"/sm", "", $val);
$val = preg_replace("/\".*/", "", $val);
$items[] = $val;
var_dump($val . "<br />");
}
}
if (in_array($testing_link, $items, true)) {
echo 'It is here!';
}
else {
echo 'it is NOT here :( ';
}
Better to use the DOMDocument to get the links into an array. Like this:
$doc = new DOMDocument();
// the string containing all the URLs and stuff
$doc->loadHTML($content);
//Extract the links from the HTML. From https://thisinterestsme.com/php-find-links-in-html/
$links = $doc->getElementsByTagName('a');
//Array that will contain our extracted links.
$extracted_links = array();
//Loop through the DOMNodeList.
//We can do this because the DOMNodeList object is traversable.
foreach ($links as $link) {
//Get the link text.
//$linkText = $link->nodeValue;
//Get the link in the href attribute.
$linkHref = $link->getAttribute('href');
}
Now all the HREFS are in the $linkHref array.
Better to use DOMDocument rather than RegEx. Much easier, and more accurate and consistent in results.
I'm trying to extract data from our JSON data based on given output fields, but I'm not getting a good result.
e.g.
Given fields that I want:
Array
(
[0] => id
[1] => name
[2] => email
[3] => optin_email
)
Those fields exist in my datastring, I want to export those to a CSV.
I can do this, hardcoded
foreach ($jsonString as $value) {
$row = [
$value->id,
$value->name,
$value->email,
$value->phone
];
print_r($row);
}
The above will give me the list/file I need. BUT, I want to make that dynamic based on the data in the array, so, fo rexample, when this is the Array:
Array
(
[0] => id
[1] => name
)
This should be my output:
foreach ($jsonString as $value) {
$row = [
$value->id,
$value->name
];
print_r($row);
}
So I need to dynamicly create the
$value->{var}
I have been trying forever, but I am not seeing it straight anymore.
Tried this:
$rowFields = '';
foreach ($export_datafields AS $v) {
$rowFields .= '$value->' . $v . ',';
}
$trimmed_row_fields = rtrim($rowFields, ',');
foreach ($jsonString as $value) {
$row = $trimmed_row_fields;
print_r($row);
}
And several variations of that:
foreach ($jsonString as $value) {
$row = [$trimmed_row_fields];
print_r($row);
}
Question is: how can I get
$value->VAR
as a valid array key when I only know the VAR name and need the prefixed $value-> object.
I ended up using the following code which works for me. If anybody still has the answer to my original question, please shoot. Always good to know it all.
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$csvFileName");
header("Pragma: no-cache");
header("Expires: 0");
$new_row = implode(",", $export_datafields) . "\n";
foreach ($jsonString as $value) {
foreach ($export_datafields AS $v) {
$new_row .= $value->$v . ',';
}
$new_row = substr($new_row, 0, -1);
$new_row .= "\n";
}
echo $new_row;
I'm trying to write a shopping list app for a website which already has ingredients listed in JSON.
The full code is at the bottom, but just to explain; What I'm aiming to do is to be able to merge the 2 arrays, adding the values from the 'quantity' when the 'name' (and preferably also the 'measure') matches.
e.g. 'Sunflower oil' is listed in both JSON feeds.
I want it to output as:
{"name":"Sunflower oil","quantity":110,"measure":"ml"}
but it currently overwrites the JSON and the output is:
{"name":"Sunflower oil","quantity":10,"measure":"ml"},
Any assistance in what I'm doing wrong would be greatly appreciated as JSON and objects/arrays aren't my strong point!
Thanks in advance - here's my code:
<?php
$a = '{"ingredients":[{"name": "Sunflower oil","quantity": 100,"measure": "ml"}]}';
$b = '{"ingredients":[{"name": "Sunflower oil","quantity": 10,"measure": "ml"},{"name": "Fennel seeds","quantity": 1,"measure": "teaspoon"},{"name": "Garlic","quantity": 1,"measure": "clove"}]}';
print_r( json_encode(array_merge(json_decode($a, true),json_decode($b, true))) );
?>
You can use the following code to get the expected result:
<?php
$a = '{"ingredients":[{"name": "Sunflower oil","quantity": 100,"measure": "ml"},{"name": "Olive oil","quantity": 50,"measure": "ml"}]}';
$b = '{"ingredients":[{"name": "Sunflower oil","quantity": 10,"measure": "ml"},{"name": "Fennel seeds","quantity": 1,"measure": "teaspoon"},{"name": "Garlic","quantity": 1,"measure": "clove"}]}';
$aArr = json_decode($a, true);
$bArr = json_decode($b, true);
$sumArr = array("ingredients" => array());
foreach ($aArr['ingredients'] as $valA) {
foreach ($bArr['ingredients'] as $keyB => $valB) {
if ($valA['name'] == $valB['name'] &&
$valA['measure'] == $valB['measure']) {
$valA['quantity'] += $valB['quantity'];
$sumArr['ingredients'][] = $valA;
unset($bArr['ingredients'][$keyB]);
continue 2;
}
}
$sumArr['ingredients'][] = $valA;
}
$sumArr['ingredients'] = array_merge($sumArr['ingredients'], $bArr['ingredients']);
print_r( json_encode( $sumArr ));
?>
in my static html site i have:
<li><a href="img/img2.jpg" rel="gallery"
class="pirobox_gall" title=""><img src="img/img2.jpg" alt=""/>
</a></li>
How in Drupal 7 I can get links to images from content type named Galery with fields: title and field_img(IMAGE). Need PHP code...
for example (its not working):
<?php
$mycontent = getcontentby_name('Galery');
foreach ($mycontent as $pic)
{
$link_to_pic = $pic['field_img']['link'];
print $link_to_pic;
}
>
Load the node in which you have your image/images by node_load($node_id), in this object you will have almost all the information related to that particular node.
<?php
$result = db_query('SELECT n.nid FROM {node} n WHERE n.type = :ntype', array(':ntype' => 'galery'));
foreach ($result as $record) {
$node = node_load($record->nid);
print '<img src="';
print file_create_url($node->field_img['und'][0]['uri']);
print '" alt=""/>';
print file_create_url($node->field_img['und'][0]['uri']);
}
?>
this code if 1 record of 'galery' - 1 image.