首页 >后端开发 >php教程 >php读xml,有问题,谢谢了。

php读xml,有问题,谢谢了。

WBOY
WBOY原创
2016-06-23 14:23:21822浏览

xml文件是:

<v time="180530" vi="1" ch="29" nls="0" title="监控实拍" code="qT4j-61ws-Q" enable="1" logo="0" wt="0" band="0"><a><f w="51" h="0" sha1="f04644" size="6012028" brt="2">http://114.80.235.12</f><f w="31" h="0" sha1="f0464" size="6012028" brt="2">http://114.80.236.202</f></a><b/></v><!-- pageview_candidate -->

我的php代码是这样写的,但读不到。谢谢了
//2.读xml$xml_array=simplexml_load_file("wc.xml"); //将XML中的数据,读取到数组对象中foreach($xml_array AS $temp){echo "<pre class="brush:php;toolbar:false">";	print_r($temp->f);echo "
";}

我的目的是要读中间的那个二个http地址。谢谢了。


回复讨论(解决方案)

xpath='//f[2]/text()'

xpath='//f[2]/text()'

谢谢了,能不能再麻烦你说的明确一下,我百度了一个,没有东西

print_r($xml_array->a->f);

$s =<<< XML<v time="180530" vi="1" ch="29" nls="0" title="监控实拍" code="qT4j-61ws-Q" enable="1" logo="0" wt="0" band="0"><a><f w="51" h="0" sha1="f04644" size="6012028" brt="2">http://114.80.235.12</f><f w="31" h="0" sha1="f0464" size="6012028" brt="2">http://114.80.236.202</f></a><b/></v>XML;$xml = simplexml_load_string($s);//正常遍历,需要确切的知道目标节点所在层次foreach($xml AS $temp){  foreach($temp->f as $v) echo "$v<br";}//xpath 查询foreach($xml->xpath('//f') as $v) echo "$v<br>";
均可得到
http://114.80.235.12
http://114.80.236.202

[code=php]$s =
谢谢大哥相助。祝你天天快乐。
我想再加强学习一下,请问这是哪方面的知识?我应该搜索什么知识啊?谢谢了。

如果你 print_r($xml_array); 就可看到

SimpleXMLElement Object(    [@attributes] => Array        (            [time] => 180530            [vi] => 1            [ch] => 29            [nls] => 0            [title] => 监控实拍            [code] => qT4j-61ws-Q            [enable] => 1            [logo] => 0            [wt] => 0            [band] => 0        )    [a] => SimpleXMLElement Object        (            [f] => Array                (                    [0] => http://114.80.235.12                    [1] => http://114.80.236.202                )        )    [b] => SimpleXMLElement Object        (        ))
这样的结构,依此书写代码是很容易的。不再赘述

XPath 是一门在 XML 文档中查找信息的语言。XPath 用于在 XML 文档中通过元素和属性进行导航。
你搜索 xpath 就可找到教程,比如  http://www.w3school.com.cn/xpath/

<?php$s =<<< XML<v time="180530" vi="1" ch="29" nls="0" title="监控实拍" code="qT4j-61ws-Q" enable="1" logo="0" wt="0" band="0"><a><f w="51" h="0" sha1="f04644" size="6012028" brt="2">http://114.80.235.12</f><f w="31" h="0" sha1="f0464" size="6012028" brt="2">http://114.80.236.202</f></a><b/></v>XML; $doc = new DOMDocument();$doc->loadXML($s);$xpath = new DOMXPath($doc);$query = '//f[1]/text()';$entries = $xpath->evaluate($query, $doc);// foreach ($entries as $entry) var_dump($entry);foreach ($entries as $entry) echo $entry->data;$xml = simplexml_load_string($s);foreach($xml->xpath('//f[1]/text()') as $v) echo $v;?>

呃,是第二个地址吧?#1的才正确
//f[ 2]/text()
xpath的计数器是从1开始的

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn