[英]php xml get element use attribute value
I am new in php. 我是php新手。
I want to parse emp_test.xml from url like : 我想从url解析emp_test.xml:
<?xml version="1.0" encoding="utf-8"?>
<all_emp>
<emp_detail>
<emp emp_name="john"><img>john_1.jpg</img></emp>
<emp emp_name="john"><img>john_2.jpg</img></emp>
<emp emp_name="john"><img>john_3.jpg</img></emp>
<emp emp_name="marry"><img>marry_1.jpg</img></emp>
<emp emp_name="marry"><img>marry_2.jpg</img></emp>
<emp emp_name="david"><img>david_1.jpg</img></emp>
</emp_detail>
</all_emp>
To get all img has attribute is john: 要获取所有img具有的属性为john:
$url = 'https://.../emp_test.xml';
$xml = simplexml_load_file("$url") or die("Error: Cannot create object");
foreach ($xml->xpath("//*[@emp_name='john']/img") as $node)
{
$img = (string) $node;
return $img;
}
I can parse xml. 我可以解析xml。
But, this is reult: 但是,这是结果:
john_1.jpg
How to get all img has attribute is john like? 如何获得所有具有属性的img像约翰一样?
john_1.jpg
john_2.jpg
john_3.jpg
Thank you for reading. 感谢您的阅读。
You can use like this. 您可以这样使用。
<?php
$url = '<?xml version="1.0" encoding="utf-8"?>
<all_emp>
<emp_detail>
<emp emp_name="john"><img>john_1.jpg</img></emp>
<emp emp_name="john"><img>john_2.jpg</img></emp>
<emp emp_name="john"><img>john_3.jpg</img></emp>
<emp emp_name="marry"><img>marry_1.jpg</img></emp>
<emp emp_name="marry"><img>marry_2.jpg</img></emp>
<emp emp_name="david"><img>david_1.jpg</img></emp>
</emp_detail>
</all_emp>';
$xml = simplexml_load_string($url) or die("Error: Cannot create object");
$imgstring ='';
foreach ($xml->emp_detail->emp as $node)
{
if (strpos((string) $node->img, 'john') !== false) {
$imgstring .= (string) $node->img.",";
}
}
print_r($imgstring);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.