Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用简单XML获取XML值_Php_Xml_Simplexml - Fatal编程技术网

Php 使用简单XML获取XML值

Php 使用简单XML获取XML值,php,xml,simplexml,Php,Xml,Simplexml,这是我第一次使用XML文件,我正在使用SimpleXML 我的印象是做$xml->dni listings->get listings by day->current->date是可能的吗?但是我不知道怎么做。目前,我能够做到这一点的唯一方法是使用以下代码。但我觉得它太冗长了,不适合做更简单的事情 我的XML文件在这里 $file=file\u获取内容('http://www.dmax.it/tvl-fe/day/?type=day&channel_code=DXIT-IT&filter=11

这是我第一次使用XML文件,我正在使用SimpleXML

我的印象是做
$xml->dni listings->get listings by day->current->date
是可能的吗?但是我不知道怎么做。目前,我能够做到这一点的唯一方法是使用以下代码。但我觉得它太冗长了,不适合做更简单的事情

我的XML文件在这里

$file=file\u获取内容('http://www.dmax.it/tvl-fe/day/?type=day&channel_code=DXIT-IT&filter=1130&date=01052013’;
$xml=新的simplexmlement($file);
foreach($xml->children()->children()作为$child)
{
echo$child->getName()。“
”; if('current'=$child->getName()){ echo$child->date.“
”; } }
好的,经过反复试验,我找到了解决方案

显然,有几种方法可以访问子元素,一种是通过调用
children()
这将使该级别的所有子元素都可用

我就是这样得到日期的:

$xml->children()->children()->current->date;
对于连字符属性,我是这样访问它们的:

$xml->children()->children()->{'previous-date'}->formatted;
我还发现了另一种方法

$namespacesMeta = $xml->getNamespaces(true);
$xml->children(@$namespacesMeta['dni-listings'])->children(@$namespacesMeta['get-listings-by-day'])->children(@$namespacesMeta['current'])->date;
我把@放在变量前面,因为从其他方面看,我得到了这个
注意:未定义的索引:在C:\xampp\htdocs\test.php的第8行
中按天获取列表,但这是另一种方法

我最初的问题是因为事情是连字符的,我的路径应该看起来更像

$xml->{'get-listings-by-day'}->current->date 

$xml
本身表示根节点,在您的示例中是
,因此在路径中保留该节点:

$dates = $xml->{'get-listings-by-day'}->current->date
我会告诉你日期的。显示所有日期:

foreach ($dates as $date) echo $date;

请注意,对于新的应用程序,不建议使用XML::Simple

我使用Perl的散列访问项目。对于简单的情况,我使用:

$xml = new  SimpleXMLElement ($file, keyattr => [] );
$xml->{dni-listings}->{get-listings-by-day}->{current}->{date};
如果您想将XML写出来,而不是让它折叠东西 与单个标记类似,您可能需要使用 ForceArray选项。这有点难,但效果很好

$xml = new  SimpleXMLElement ($file, ForceArray => 1, keyattr => [] );
$xml->{dni-listings}[0]->{get-listings-by-day}[0]->{current}[0]->{date}[0];

你的回答似乎是正确的。它还向Jonathan展示了如何压缩代码并防止他在这里错误地使用名称空间(因为文档中根本没有名称空间)。Counter upvote已经解锁。只是一些参考(到目前为止,我看到你已经解决了它,但它可能很有趣):和著名的你得到警告,因为没有这些名称空间。与其隐藏警告(
@
-operator),不如修复原因;)只是不要在没有名称空间的地方使用名称空间;)
$xml = new  SimpleXMLElement ($file, ForceArray => 1, keyattr => [] );
$xml->{dni-listings}[0]->{get-listings-by-day}[0]->{current}[0]->{date}[0];