Extracting attribute with simplexml_load_string - php

I'm trying to extract the href attribute of link as a string.
Read More
I'm using the following to read the extract the attribute:
$link = simplexml_load_string($ad['meta_value']);
$order['logo'] = $logo['href']->asXML();
Instead of getting http://example.com I'm getting href="http://example.com". Beside using str_replace() is there a way to extract the attribute as a string?

Treat #attributes as object and convert to string:
$link = simplexml_load_string($ad['meta_value']);
echo (string) $link->attributes()->href;

Related

Preg Replace text based on string

i am trying to figure out why this has no result.
I am fetching data from wp database
$global_notice2 = get_post_meta($post->ID,'_global_notice', true);
This contains an a href link i wish to manipulate using preg replace before displaying it for the user such as
preg_replace('/<a(.*?)href="(.*?)"(.*?)>/', '', $global_notice2 );
Now we display the data
$notice2 = "<p>$alternative_content$global_notice2</p>";
The data is unmodified, what am i doing wrong?
preg_replace don't modify the argument, you need to catch the return like this :
$global_notice2 = preg_replace('/<a(.*?)href="(.*?)"(.*?)>/', '', $global_notice2);
See preg_replace documentation

Convert element and return contents of element using php

I have this element in the DOM derived from a php command.
Atención al cliente
Here is the php command that generates the element above:
<?php icl_link_to_element(2880);?>
I need to convert this element in some way so that I only end up with string 'Atención al cliente' stored in a variable so I can use this string for other purposes.
What is the best way to get this done in PHP?
Use Preg_match
<?php
$str = 'Atención al cliente';
preg_match('/\>(.*)\</i', $str, $matches);
$wantedString = $matches[1];
echo $wantedString;
?>
For Wordpress edit:
I think you should get the page using $page = icl_object_id(2880, 'page', true); then get the title with get_the_title($page); or var_dump that $page to see if you can get what you want

Taking a section of a PHP PDO string and insert it into img element

just a quick question.
So I am fetching a string from my SQL table using PDO and printing it to my front end, I am currently using this code:
'.implode('</div><div>', explode(',', $row["String"])) .'
As you can see this code is exploding the string with each comma and putting each into a div.
I am now wanting to change the output but having a bit of trouble taking the first part of the string and putting it into an img.
Here is an example of the column in my SQL table:
http://www.imgurl.com/image.jpg,http://www.imgurl.com/image2.jpg,http://www.imgurl.com/image3.jpg, http://www.imgurl.com/image4.jpg
As you can see they are separated by a comma, I want to insert that first jpg url into the src section of a img element.
How can I do this?
If you're just wanting to 1 liner it, then you could do:
.'<img src="'.implode('"/><img src="',explode(',', $row["String"])).'"/>'.
Which will produce something like:
<img src="http://www.imgurl.com/image.jpg"/><img src="http://www.imgurl.com/image2.jpg"/><img src="http://www.imgurl.com/image3.jpg"/><img src="http://www.imgurl.com/image4.jpg"/>
To just get the first array element of a string in php 5.4+:
echo '<img src="'.explode(',', $row['String'])[0].'"/>';
Otherwise:
$parts = explode(',', $row['String']);
echo '<img src="'.$parts[0].'"/>';
$images = explode(',', $row['String']);
echo '<img src="'.$images[0].'"/>';

PHP getting and setting attributes on HTML Elements [duplicate]

This question already has answers here:
PHP Getting and Setting tag attributes
(2 answers)
Closed 9 years ago.
I'm looking for a solution for manipulating html elements via php.
I was reading http://www.php.net/manual/en/book.dom.php but I didn't get to far.
I'm taking an "iframe" element ( video embed code ) and trying to modify it before echoing it.
I would like to add some parameters to the "src" attribute.
Based on the answer from https://stackoverflow.com/a/2386291 I'am able to iterate through element attributes.
$doc = new DOMDocument();
// $frame_array holds <iframe> tag as a string
$doc->loadHTML($frame_array['frame-1']);
$frame= $doc->getElementsByTagName('iframe')->item(0);
if ($frame->hasAttributes()) {
foreach ($frame->attributes as $attr) {
$name = $attr->nodeName;
$value = $attr->nodeValue;
echo "Attribute '$name' :: '$value'<br />";
}
}
My questions are:
How could I get the attribute value without iterating through all attributes of the element and checking to see if the current element is the one I'm looking for?
How can I set the attribute value on the element?
I prefer not to use regex for this because I would like it to be future proof. If the "iframe" tag is properly formatted, should I have any problems with this?
iframe example:
<iframe src="http://player.vimeo.com/video/68567588?color=c9ff23" width="486"
height="273" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen>
</iframe>
// to get the 'src' attribute
$src = $frame->getAttribute('src');
// to set the 'src' attribute
$frame->setAttribute('src', 'newValue');
To change the URL, you should first use parse_url($src), then rebuild it with your new query arguments, for example:
$parts = parse_url($src);
extract($parts); // creates $host, $scheme, $path, $query...
// extract query string into an array;
// be careful if you have magic quotes enabled (this function may add slashes)
parse_str($query, $args);
$args['newArg'] = 'someValue';
// rebuild query string
$query = http_build_query($args);
$newSrc = sprintf('%s://%s%s?%s', $scheme, $host, $path, $query);
I don't understand why you need to iterate through the attributes to determine if this is the element you are looking for. You seem to only be grabbing the first iframe element, so I am not clear what you first question is really about.
For your second question, you just need to use setAttribute() method of DOMElement like this:
$frame->setAttribute($attr_key, $attr_value);
You shouldn't have problems parsing the HTML you have shown.

Strip directory structure in HTML

I have a PHP application that reads in a bit of HTML. In this HTML there may be an img tag. What I want to do is strip the directory structure from the src of the image tag e.g.
<img src="dir1/dir2/dir3/image1.jpg>
to
<img src="image1.jpg">
Anyone have any pointers?
Thanks,
Mark
As a suggestion, rather than using regex, you may be better off using something like the SimpleXML class to traverse the HTML, that way you'd be able to find the img tags and their src attribute then change it easily. Rather than having to try and parse a whole document with regex. After you've done that you'd be able to just explode the string using the "/" delimiter and use the last value of the exploded array as the src attribute.
PHP.net's SimpleXML Manual: http://php.net/manual/en/book.simplexml.php
This is a tutorial how to change all links in a HTMl document: Scraping Links From HTML.
With a slight modification of the example, this could do it:
<?php
require('FluentDOM/FluentDOM.php');
$html = '<img src="dir1/dir2/dir3/image1.jpg">';
$fd = FluentDOM($html, 'html')->find('//img[#src]')->each(
function ($node) use ($url) {
$item = FluentDOM($node);
$item->attr('href', basename($item->attr('src')));
}
);
$fd->contentType = 'xml';
header('Content-type: text/xml');
echo $fd;
?>
If you want to try this with regexp this could work:
$subject = "dir1/dir2/dir3/image1.jpg";
$pattern = '/^.*\//';
$result = preg_replace($pattern, '', $subject);

Categories