Get the feed value from particular string in php - php

I have the below feed value
<item>
<description><strong>Contact Number:</strong> +91-00-000-000<br /><br /><strong>Rate:</strong> xx.xx<br /><br /><strong>Fees and Comments:<br /></strong><ul><li>$0 fees</li><li>Indicative Exchange Rate</li></description>
</item>
Now i wanna get Contact number and rate as well as Fees and comments in separte value.
how can i get this value ..any one????

Description
You should probably read this with a parsing engine. however if your use case is this simple then this regex will:
capture each of the fields
allow the fields to appear in any order
^(?=.*?Contact\sNumber:<\/strong>([^<]*))(?=.*?Rate:<\/strong>([^<]*))(?=.*?Fees\sand\sComments:.*?<li>([^<]*)<.*?<li>([^<]*)<)
Live Example: http://www.rubular.com/r/j0aStij3L8

It kind of depends on what reliable patterns there are to the rest of your feed (or future feeds). It doesn't look like an XML parser is going to work here as the example doesn't look like well formed XML.
A good way to start is using explode to split the string into an array of strings, it looks like is a good delimiter to split on. So this would look like:
$split_feed = explode("<br />",$feed);
where $feed is your feed input in the question, and $split_feed will be your output array.
Then, from that split feed, you can use strpos (or stripos) to test for keys in your string, to determine which field it references, and replace to get the value out of the key/value string.

I think this is you want
<?php
$value = '<strong>Contact Number:</strong> +91-00-000-000<br /><br />
<strong>Rate:</strong> xx.xx<br /><br />
<strong>Fees and Comments:<br /></strong><ul><li>$0 fees</li>
<li>Indicative Exchange Rate</li>';
$steps = explode('<br /><br />', $value);
$step_2_for_contact_number = explode('</strong>', $steps[0]);
$contact_number = $step_2_for_contact_number[1];
$step_for_rate = explode('</strong>', $steps[1]);
$rate = $step_for_rate[1];
$feed_n_comment_s_1 = explode('</li>', $steps[2]);
$feed_n_comment_s_2 = explode('<li>', $feed_n_comment_s_1[0]);
$feed_n_comment = $feed_n_comment_s_2[1];
echo $contact_number;
echo "<br/>";
echo $rate;
echo "<br/>";
echo $feed_n_comment;
?>

You can also have a look at this pattern: (uses named groups)
(?<key>[a-zA-Z\d\s]+)(?=\:).*?\>(?<value>[^<]+)
Live Demo

Related

Fail to split a string in array by a character

I am working on a Wordpress website and I want to get some order details right after the submission. One of them, returned with a long string which I want to split and format it as I need. Here is the example:
echo $order->get_formatted_shipping_address();
My name<br />My address<br />My postcode
I try to split the string in the <br /> to use each of the fields in a different place. I tried like this:
$data = explode("<br />", $order->get_formatted_shipping_address());
$name = $data[0];
$address = $data[1];
$post = $data[2];
However, the <br /> keeps staying in the string and the $name has the whole string as in $data.
Any idea?
Tried the following on WooCommerce 2.6.1
$data = explode('<br/>',$order->get_formatted_shipping_address());
Note that the delimiter is <br/> and not as you used it <br />, yours has an extra space.
As an alternative, instead of explode you should use the magic properties from the class WC_Abstract_Order.
Example
print $order->shipping_first_name;
print $order->shipping_address_1;
print $order->shipping_postcode;
This will output the fields without going through the implode that happens inside get_formatted_shipping_address()
Your code should work, I even tested it on my machine. Put this code in some new file and just test it to see if it gives the wanted result. If it does, then you're making a mistake on the place. Are you sure you are using the right variables?
<?php
class wp {
public function get_formatted_shipping_address() {
return "My name<br />My address<br />My postcode";
}
}
$order = new wp;
$data = explode("<br />", $order->get_formatted_shipping_address());
print_r($data);
$name = $data[0];
$address = $data[1];
$post = $data[2];

How can I sanitise the explode() function to extract only the marker I require?

I have some php code that extracts a web address. The object I have extracted is of the form:
WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults
Now in PHP I have called this object $linkHREF
I want to extract the id element only and put it into an array (I'm bootstrapping this process to get multiple id's)
So the command is:
$detailPagePathArray = explode("id=",$linkHREF); #Array
Now the problem is the output of this includes what comes after the id tag, so the output looks like:
echo $detailPagePathArray[0] = WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&w
echo $detailPagePathArray[1] = bf&page=1&
echo $detailPagePathArray[2] = 16123012&source=searchresults
Now the problem is obvious, where it'd firstly picking up the "id" in the "wid" marker and cutting it there, however the secondary problem is it's also picking up all the material after the actual "id". I'm just interested in picking up "16123012".
Can you please explain how I can modify my explode command to point it to the particular marker I'm interested in?
Thanks.
Use the built-in functions provided for the purpose.
For example:
<?php
$url = 'http://www.example.com?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults';
$qs = parse_url($url);
parse_str($qs['query'], $vars);
$id = $vars['id'];
echo $id; // 16123012
?>
References:
parse_url()
parse_str()
if you are sure that you are getting &id=123456 only once in your object, then below
$linkHREF = "WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults";
$str = current(explode('&',end(explode('&id', $linkHREF,2))));
echo "id" .$str; //output id = 16123012

how to display SimpleXMLElement with php

Hi I have never used xml but need to now, so I am trying to quickly learn but struggling with the structure I think. This is just to display the weather at the top of someones website.
I want to display Melbourne weather using this xml link ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml
Basically I am trying get Melbourne forecast for 3 days (what ever just something that works) there is a forecast-period array [0] to [6]
I used this print_r to view the structure:
$url = "linkhere";
$xml = simplexml_load_file($url);
echo "<pre>";
print_r($xml);
and tried this just to get something:
$url = "linkhere";
$xml = simplexml_load_file($url);
$data = (string) $xml->forecast->area[52]->description;
echo $data;
Which gave me nothing (expected 'Melbourne'), obviously I need to learn and I am but if someone could help that would be great.
Because description is an attribute of <area>, you need to use
$data = (string) $xml->forecast->area[52]['description'];
I also wouldn't rely on Melbourne being the 52nd area node (though this is really up to the data maintainers). I'd go by its aac attribute as this appears to be unique, eg
$search = $xml->xpath('forecast/area[#aac="VIC_PT042"]');
if (count($search)) {
$melbourne = $search[0];
echo $melbourne['description'];
}
This is a working example for you:
<?php
$forecastdata = simplexml_load_file('ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml','SimpleXMLElement',LIBXML_NOCDATA);
foreach($forecastdata->forecast->area as $singleregion) {
$area = $singleregion['description'];
$weather = $singleregion->{'forecast-period'}->text;
echo $area.': '.$weather.'<hr />';
}
?>
You can edit the aforementioned example to extract the tags and attributes you want.
Always remember that a good practice to understand the structure of your XML object is printing out its content using, for instance, print_r
In the specific case of the XML you proposed, cities are specified through attributes (description). For this reason you have to read also those attributes using ['attribute name'] (see here for more information).
Notice also that the tag {'forecast-period'} is wrapped in curly brackets cause it contains a hyphen, and otherwise it wouldn generate an error.

need help in Regular Expression

I am in a weird scenerio where I need to show the content in multiple columns. I am using css3 column-cont and jquery plugin columnizer for older versions of IE.
The problem is that I do not have complete control over the data as it is served by an external webservice.
In most cases the content is wrapped in multiple paragraph tabs
Content#1
<p><strong>Heading</strong><br>This is a content</p>
<p><strong>Heading</strong><br>This is a content</p>
But In few cases the data is not wrapped in <p> tag and looks like below:
Content#2
<strong>Day 1: xyz </strong><br>
lorem lipsum <br> <br>
<strong>Dag 2: lorem lipsum</strong><br>
Morgonflyg till Arequipa i södra Peru.
<br> <br>
The real problem is jquery columnizer plugin hangs up the browser with this markup when it is asked to columnize such content.
Now I want to transform Content#2 to Content#1 with the help of regular expression,ie wrap the contents into sensible paragraphs. I hope I have made myself clear
I am using PHP.
Thank you in advance!
Your content is not stable and Regular Expression won't do magics with distinct contents like this. With this being said, whenever you're receiving the data from the other website, there might be a high chance that someday it'll return different pattern so your rules won't be good anymore. You need to have a reliable source to get a reliable result.
This is a filthy string manipulation but it'll get what you need if the pattern stays consistent. And, I still insist that you have to use a reliable source.
$str = "<strong>Day 1: xyz </strong><br>
lorem lipsum <br> <br>
<strong>Dag 2: lorem lipsum</strong><br>
Morgonflyg till Arequipa i södra Peru.
<br> <br> ";
function parse($data)
{
if(substr($data, 0, 3) == "<p>") return $data;
$chunks = explode("<strong>", $data);
$out = array();
foreach($chunks as $chunk)
{
$item = $chunk;
$last_br = strpos($item, "<br> <br>");
if($last_br > -1){ $item = substr($item, 0, $last_br); }
$item = "<p>" . $item . "</p>";
$out[] = $item;
}
return implode("\n", $out);
}
echo parse($str);
You can use this pattern:
/(?<!^<p>)(<strong>.*?)(<strong>.*)$/gs
Demo
Notice that the exclusion in the negative lookbehind will ONLY work if your strings starts with a <p>... so consider to trim it before applying your regex...
<br> tags has to be removed using another regex or str_replace()
Also, consider maybe using another aproach than Regex to parse DOM HTML...

PHP - list all form elements within a div

Is there a built in php function that will return an array (or some sort of list) of all the form elements within a div or within a specific form by either name or id?
My limited experience in javascript tells me that this can probably be occomplished with javascript but i am wondering if it can be done in php. Thanks for your help.
My only other alternative would be to define a variable at the bottom of each form element like:
$allElements = 'name';
$allElements .= ', phone';
$allElements .= ', email';
and so on.
I am wondering if there is a short cut to this method?
You are going to want to parse the HTML.
$HTML = '<div name="phone"></div>';
$string = strstr($HTML, 'name=\"');
$string = strstr($string, '\"');
something like that...
these are your best friends:
stripos()
strrpos()
strripos()
strstr()
strpbrk()
substr()
Don't really know what you exactly mean.
All variables from a sent form are stored in the $_POST global variable. This will show you the list:
if ($_POST) {
echo '<pre>';
echo print_r($_POST);
echo '</pre>';
}
Maybe you need to parse HTML with PHP - see the answer above.

Categories