So right now I have 2 php codes that work exactly as they are supposed to
the first one pulls all info from the "src" of an "img" tag
<?php
$url="foo";
$html = file_get_contents($url);
$doc = new DOMDocument();
#$doc->loadHTML($html);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
echo $tag->getAttribute('src') . "<br>";
}
?>
the second one is designed to pull a string of characters from between two others strings
<?php
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)
?>
what I need is to figure out how to use the second code to only pull a piece of the "src" and replace it for as long as there are still "img" tags to process
so if the tag comes back "/pics/foo.jpg" i can remove the "/pics/" and the ".jpg" leaving me with just "foo"
i hope i have made some sense. thanks
Why do you want to use the second code? You can do it with exploding the fullstring:
$exploded_tag = explode($tag,'\');
Then you need the last element of the string (foo.jpg):
$last_part = end($exploded_tag);
Then you have to explode it and take the first element (foo):
$exploded_lastpart = explode($last_part,'.');
$piece = $exploded_lastpart[0];
You don't need second code. There is function in PHP called pathinfo(). So you can just do:
$path_parts = pathinfo('/pics/foo.jpg');
echo $path_parts['filename'];
Related
how to extract specific string after specific word using html dom in php. I have
<div class="abc">
<script type="text/javascript">
var flashvars = { word : path } </script>
Now i want to extract path after word
thanks for your response.
I got the solution for what i was looking.
Here is the code in case someone needs it.
Explanation :
'$results' is the curl response.
Enter div class name (which you want to fetch) inside "$xpath->query() function"
You will get source code for entire class inside "$tag->textContent"
$dom = new DOMDocument();
$dom->loadHTML($results);
$xpath = new DOMXPath($dom);
$tags = $xpath->query('//div[#class="e"]');
foreach ($tags as $tag)
{
echo "<br>----------<br>";
var_dump($tag->textContent);
echo "<br>----------<br>";
}
Now you have your required class' html source inside "$tag->textContent".
Now you can fetch anything from the string between "start" and "end" points using below function.
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
In my case i used it like this :
$price = get_string_between($tag->textContent,'swf', '+');
echo $price;
Here "swf" is the starting point of the path and "+" is the end point.
Hope it saves somebody else time :)
I am facing a problem that I can't get my head around. I thought I would turn to the experts once again to shine some light.
I have a HTML template and within the template I have delimiters like:
[has_image]<p>The image is <img src="" /></p>[/has_image]
These delimiters may have multiple occurances within the template and below is what I am trying to achieve:
Find all occurances of these delimiters and replace the content between these delimiters with an image source or replace it empty if image doesn't exist but still keep the value/content of the remaining template.
Below is my code that works only for one occurance but struggling to accomplish it for multiple occurances.
function replace_text_template($template_body, $start_tag, $end_tag, $replacement = ''){
$occurances = substr_count($template_body, $start_tag);
$x = 1;
while($x <= $occurances) {
$start = strpos($template_body, $start_tag);
$stop = strpos($template_body, $end_tag);
$template_body = substr($template_body, 0, $start) . $start_tag . $replacement . substr($template_body, $stop);
$x++;
}
return $template_body;
}
$template_body will have HTML code with delimiters
replace_text_template($template_body, "[has_image]", "[/has_image]");
Whether I remove the while loop it still works for a single delimiter.
I have managed to solve the problem. If anybody finds this useful please feel free to use the code. However, if anyone finds a better way please do share it.
function replace_text_template($template_body, $start_tag, $end_tag, $replacement = ''){
$occurances = substr_count($template_body, $start_tag);
$x = 1;
while($x <= $occurances) {
$start = strpos($template_body, $start_tag);
$stop = strpos($template_body, $end_tag);
$template_body = substr($template_body, 0, $start) . $start_tag . $replacement . substr($template_body, $stop);
$template_body = str_replace($start_tag.''.$end_tag, '', $template_body); // replace the tags so on next loop the position will be correct
$x++;
}
return $template_body;
}
function replace_text_template($template_body, $start_tag, $replacement = '') {
return preg_replace_callback("~\[".preg_quote($start_tag)."\].*?\[\/".preg_quote($start_tag)."\]~i", function ($matches) use ($replacement) {
if(preg_match('~<img.*?src="([^"]+)"~i', $matches[0], $match)) {
if (is_array(getimagesize($match[1]))) return $match[1];
}
return $replacement;
}, $template_body);
}
$template_body = <<<EOL
text
[has_image]<p>The image is <img src="" /></p>[/has_image]
abc [has_image]<p>The image is <img src="http://blog.stackoverflow.com/wp-content/themes/se-company/images/logo.png" /></p>[/has_image]xyz
EOL;
echo replace_text_template($template_body, "has_image", "replacement");
Returns:
text
replacement
abc http://blog.stackoverflow.com/wp-content/themes/se-company/images/logo.pngxyz
I have the below code wich is extracting the Artist name from a XML file with the ref asrist code.
<?php
$dom = new DOMDocument();
$dom->load('http://www.bookingassist.ro/test.xml');
$xpath = new DOMXPath($dom);
echo $xpath->evaluate('string(//Artist[ArtistCode = "COD Artist"] /ArtistName)');
?>
The code that is pulling the artistcode based on a search
<?php echo $Artist->artistCode ?>
My question :
Can i insert the variable generated by the php code into the xml request string ?
If so could you please advise where i start reading ...
Thanks
You mean the XPath expression. Yes you can - it is "just a string".
$expression = 'string(//Artist[ArtistCode = "'.$Artist->artistCode.'"]/ArtistName)'
echo $xpath->evaluate($expression);
But you have to make sure that the result is valid XPath and your value does not break the string literal. I wrote a function for a library some time ago that prepares a string this way.
The problem in XPath 1.0 is that here is no way to escape any special character. If you string contains the quotes you're using in XPath it breaks the expression. The function uses the quotes not used in the string or, if both are used, splits the string and puts the parts into a concat() call.
public function quoteXPathLiteral($string) {
$string = str_replace("\x00", '', $string);
$hasSingleQuote = FALSE !== strpos($string, "'");
if ($hasSingleQuote) {
$hasDoubleQuote = FALSE !== strpos($string, '"');
if ($hasDoubleQuote) {
$result = '';
preg_match_all('("[^\']*|[^"]+)', $string, $matches);
foreach ($matches[0] as $part) {
$quoteChar = (substr($part, 0, 1) == '"') ? "'" : '"';
$result .= ", ".$quoteChar.$part.$quoteChar;
}
return 'concat('.substr($result, 2).')';
} else {
return '"'.$string.'"';
}
} else {
return "'".$string."'";
}
}
The function generates the needed XPath.
$expression = 'string(//Artist[ArtistCode = '.quoteXPathLiteral($Artist->artistCode).']/ArtistName)'
echo $xpath->evaluate($expression);
I have an XML file which is as follows. I want to parse this XML file using PHP.
<id_list>
-
<ids>
<id>195002349</id>
<id>374487611</id>
<id>192983648</id>
<id>168378766</id>`
<id>161573001</id>
</ids>
<next_cursor>0</next_cursor>
<previous_cursor>0</previous_cursor>
</id_list>
I want the output in the form:
Id1=195002349 Id2=374487611 Id3=192983648 Id4=168378766 Id5=161573001
When reading the XML (with SimpleXMLElement($file)), use XPath to search for "ids", and do a while loop to read the element`s text.
Like so:
$notes = new SimpleXMLElement('test2.xml', NULL, true);
$all = array();
$results = $notes->xpath("/id_list/ids/id");
foreach($results as $to){
echo "<br>".$to;
$all[]=(string)$to;
}
print_r($all);
This is a handy little function to strip out a string between two specified pieces of text. This could be used to parse XML text, bbCode, or any other delimited code/text for that matter.
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:
a wrong one
the right one
a wrong one
That is, to get the value of the href attribute if the link has a particular text.
This will select the attributes:
"//a[text()='the right one']/#href"
i think this is the best solution, you can use each of them as an array element
$String= '
a wrong one
the right one
a wrong one
';
$array=get_all_string_between($String,'href="','">');
print_r($array);//just to see what is inside the array
//now get each of them
foreach($array as $value){
echo $value.'<br>';
}
function get_all_string_between($string, $start, $end)
{
$result = array();
$string = " ".$string;
$offset = 0;
while(true)
{
$ini = strpos($string,$start,$offset);
if ($ini == 0)
break;
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
$result[] = substr($string,$ini,$len);
$offset = $ini+$len;
}
return $result;
}
"//a[#href='http://example.com']"
I'd use an opensource class like simple_html_dom.php
$oHtml = new simple_html_dom();
$oHtml->load($sBody)
foreach($oHtml->find('a') as $oElement) {
echo $oElement->href
}
Here's a full example using SimpleXML:
$xml = '<html>a wrong one'
. 'the right one'
. 'a wrong one</html>';
$tree = simplexml_load_string($xml);
$nodes = $tree->xpath('//a[text()="the right one"]');
$href = (string) $nodes[0]['href'];