PHP get a div from page x [duplicate]

2019-08-08 02:44发布

This question already has an answer here:

I wanna extract some html from page Y

for example site is
<head>xxxx</head>
<body>....<div id="ineedthis_code"> </div> ...</body>

it is possible to do this file_get_contents ?! i need only that div nothing else

1条回答
闹够了就滚
2楼-- · 2019-08-08 03:13

Without using a special library (which is the best way in most cases), you can use the explode-function:

$content = file_get_contents($url);
$first_step = explode( '<div id="YOUR ID HERE">' , $content ); // So you will get two array elements

$second_step = explode("</div>" , $first_step[1] ); // "1" depends, if you have more elements with this id (theoretical) 

echo $second_step[0]; // You will get the first element with the content within the DIV :)

Please note, it's only an example without error handling. It also works onlny on a special case; not if the html structure ist changing. Even simple spaces can break this code. So you should better use a parsing library ;-)

查看更多
登录 后发表回答