php parse xml use exactly attribute

Home / Uncategorized / php parse xml use exactly attribute

Question:
Input XML:$url = ‘


john_1.jpg
john_2.jpg
john_3.jpg
jo_1.jpg
jo_2.jpg
david_1.jpg

‘;

$xml = simplexml_load_string($url) or die("Error: Cannot create object");
$imgstring =”;
foreach ($xml->emp_detail->emp as $node ) {
if (strpos((string) $node->attributes()->emp_name, "jo") !== false) {
$imgstring .= (string) $node->img . "
";
}
}
echo ($imgstring);

Current result:john_1.jpg
john_2.jpg
john_3.jpg
jo_1.jpg
jo_2.jpg

But i want get only img with attribute is "jo" like,

Expected:jo_1.jpg
jo_2.jpg

How to do it?


Answer:
You are doing one thing wrong here strpos is to check position of substring and jo is also a substring of john that’s why you are getting all the values Instead you can simple use == for comparison.

Try this code snippet here

Change this to:if (strpos((string) $node->attributes()->emp_name, "jo") !== false) {

This:if ($node->attributes()->emp_name== "jo") {
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *